简体   繁体   English

使用GCM和Django处理Android中的推送通知

[英]Handling Push notifications in android using GCM and Django

I'm new to android programming, there are two types of push notifications in my app (for eg- one for Notices and other for News), how can I differentiate these notifications and how can I open different activities by clicking them separately? 我是Android编程的新手,我的应用程序中有两种类型的推送通知(例如-一种用于通知,另一种用于新闻),如何区分这些通知,以及如何通过分别单击它们来打开不同的活动?

Random random = new Random();
int notifyID = random.nextInt(9999 - 1000) + 1000;
NotificationCompat.Builder builder;

public GCMNotificationIntentService() {
    super("GcmIntentService");
}


@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {

            sendNotification("Send error: " + extras.toString());

        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {

            sendNotification("Deleted messages on server: " + extras.toString());

        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

            if (ApplicationConstants.MSG_KEY.equals("message")) {
                sendNotification("Notice: " + extras.get(ApplicationConstants.MSG_KEY));
            }
        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

private void sendNotification(String msg) {

    Intent resultIntent = new Intent(this, NoticeActivity.class);
    resultIntent.putExtra("msg", msg);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder mNotifyBuilder;
    NotificationManager mNotificationManager;

    Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_icon);

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mNotifyBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Title")
            .setContentText("You've received a new message.")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setAutoCancel(true)
            .setLargeIcon(largeIcon)
            .setPriority(Notification.PRIORITY_HIGH);

    /* Notification Icon as per API level*/

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mNotifyBuilder.setSmallIcon(R.drawable.icon_s);
        //    mNotifyBuilder.setColor(getResources().getColor(R.color.white));
    } else {
        mNotifyBuilder.setSmallIcon(R.mipmap.ic_icon);
    }

    // Set pending intent
    mNotifyBuilder.setContentIntent(resultPendingIntent);

    // Set Vibrate, Sound and Light
    int defaults = 0;
    defaults = defaults | Notification.DEFAULT_LIGHTS;
    defaults = defaults | Notification.DEFAULT_VIBRATE;
    defaults = defaults | Notification.DEFAULT_SOUND;

    mNotifyBuilder.setDefaults(defaults);
    // Set the content for Notification
    mNotifyBuilder.setContentText(msg);
    // Set autocancel
    mNotifyBuilder.setAutoCancel(true);
    // Post a notification
    mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}

For this functionality, you have to generate 2 different Notification with different notification ids. 对于此功能,您必须生成两个具有不同通知ID的不同通知。

Let me explain 让我解释

Define two int variable for notification id. 为通知ID定义两个int变量。

final int NOTIFICATION_NOTICE = 0;
final int NOTIFICATION_NEWS = 1;

See below code. 参见下面的代码。

For NOTICE Notification 对于通知通知

NotificationManager notificationManager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);

Intent noticeIntent = new Intent(context, NoticeActivity.class);   // Activity Name as you want to Open on click

noticeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
        | Intent.FLAG_ACTIVITY_SINGLE_TOP |  Intent.FLAG_AUTO_CANCEL);

PendingIntent intent = PendingIntent.getActivity(context, 0,
        noticeIntent, 0);

notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_NOTICE, notification);   // Notification id for differentiate Notification

For NEWS Notification 对于新闻通知

NotificationManager notificationManager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);

Intent newsIntent = new Intent(context, NewsActivity.class);     // Activity Name as you want to Open on click

newsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
        | Intent.FLAG_ACTIVITY_SINGLE_TOP |  Intent.FLAG_AUTO_CANCEL);

PendingIntent intent = PendingIntent.getActivity(context, 0,
        newsIntent, 0);

notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_NEWS , notification);     // Notification id for differentiate Notification

EDIT 编辑

public class GcmIntentService extends IntentService {

   final int NOTIFICATION_NOTICE = 0;
   final int NOTIFICATION_NEWS = 1;
   NotificationCompat.Builder builder;

public GCMNotificationIntentService() {
    super("GcmIntentService");
}


@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {

            sendNotification("Send error: " + extras.toString());

        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {

            sendNotification("Deleted messages on server: " + extras.toString());

        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

            if (ApplicationConstants.MSG_KEY.equals("message")) {
                sendNotification("Notice: " + extras.get(ApplicationConstants.MSG_KEY), extras.get("notificationType"));
            }
        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

private void sendNotification(String msg, String type) {

    if(type.equalsignoreCase("Notice")){
     NotificationCompat.Builder mNotifyBuilder;
     NotificationManager mNotificationManager;

     Intent resultIntent = new Intent(this, NoticeActivity.class);
     resultIntent.putExtra("msg", msg);
     PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_ONE_SHOT);

     Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_icon);

     mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

     // Set Vibrate, Sound and Light
     int defaults = 0;
     defaults = defaults | Notification.DEFAULT_LIGHTS;
     defaults = defaults | Notification.DEFAULT_VIBRATE;
     defaults = defaults | Notification.DEFAULT_SOUND;


     mNotifyBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Title")
            .setContentText("You've received a new message.")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setAutoCancel(true)
            .setDefaults(defaults);
            .setLargeIcon(largeIcon)
            .setPriority(Notification.PRIORITY_HIGH);

    /* Notification Icon as per API level*/

      if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mNotifyBuilder.setSmallIcon(R.drawable.icon_s);
        //    mNotifyBuilder.setColor(getResources().getColor(R.color.white));
      } else {
        mNotifyBuilder.setSmallIcon(R.mipmap.ic_icon);
      }

    // Set pending intent
     mNotifyBuilder.setContentIntent(resultPendingIntent);
    // Post a notification
    mNotificationManager.notify(NOTIFICATION_NOTICE, mNotifyBuilder.build());
  } 
  else if(type.equalsignoreCase("News")){
     NotificationCompat.Builder mNotifyBuilder;
     NotificationManager mNotificationManager;

     Intent resultIntent = new Intent(this, NewsActivity.class);
     resultIntent.putExtra("msg", msg);
     PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_ONE_SHOT);

     Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_icon);

     mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

     // Set Vibrate, Sound and Light
     int defaults = 0;
     defaults = defaults | Notification.DEFAULT_LIGHTS;
     defaults = defaults | Notification.DEFAULT_VIBRATE;
     defaults = defaults | Notification.DEFAULT_SOUND;


     mNotifyBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Title")
            .setContentText("You've received a new message.")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setAutoCancel(true)
            .setDefaults(defaults);
            .setLargeIcon(largeIcon)
            .setPriority(Notification.PRIORITY_HIGH);

    /* Notification Icon as per API level*/

      if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mNotifyBuilder.setSmallIcon(R.drawable.icon_s);
        //    mNotifyBuilder.setColor(getResources().getColor(R.color.white));
      } else {
        mNotifyBuilder.setSmallIcon(R.mipmap.ic_icon);
      }

    // Set pending intent
     mNotifyBuilder.setContentIntent(resultPendingIntent);
    // Post a notification
    mNotificationManager.notify(NOTIFICATION_NEWS , mNotifyBuilder.build());
  }
}
}

Here, No need to two Push notification class or methods. 在这里,不需要两个Push通知类或方法。

Discuss with your web team and tell them give new key in which they will give you notification type.(ie. Notice or News) 与您的网络团队讨论,并告诉他们提供新的密钥,以便在其中提供通知类型。(例如,通知或新闻)

ie {type = "Notice",message =" My message"}; 即{type =“ Notice”,message =“我的消息”};

And

{type = "News",message =" My message"}; {type =“ News”,message =“ My message”};

SOLVED by using this trick- 通过使用此技巧解决了-

if (ApplicationConstants.MSG_KEY.equals("message")) {

                    String strNotification = ("" + extras.get(ApplicationConstants.MSG_KEY));
                    String arr[] = strNotification.split(" ", 2);
                    String firstWord = arr[0];
                    System.out.println("string: " + firstWord);

                    if (firstWord.equalsIgnoreCase("NOTICE:")) {
                        sendNotification("" + extras.get(ApplicationConstants.MSG_KEY));
                    } else if (firstWord.equalsIgnoreCase("NEWS:")) {
                        sendNotificationNews("" + extras.get(ApplicationConstants.MSG_KEY));
                    }

                }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM