【问题标题】:How to receive more than one notification from gcm?如何从 gcm 接收多个通知?
【发布时间】:2014-02-24 07:04:12
【问题描述】:

我正在开发一个应用程序,我必须从 gcm 服务器接收通知。我成功收到通知。在这里我有问题。我成功阅读了多个通知,但所有消息通知仅显示一条消息,即仅显示最后一条数据。

我的代码

 public class GcmIntentService extends IntentService{
    Context context;
    public static  int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    public static final String TAG = "GCM Demo";

    public GcmIntentService() {
        super("GcmIntentService");
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // TODO Auto-generated method stub
        Bundle extras = intent.getExtras();
        String msg = intent.getStringExtra("message");
        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());
                // If it's a regular GCM message, do some work.
                } else if (GoogleCloudMessaging.
                        MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                    // This loop represents the service doing some work.
                    for (int i=0; i<5; i++) {
                        Log.i(TAG, "Working... " + (i+1)
                                + "/5 @ " + SystemClock.elapsedRealtime());
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                        }
                    }
                    Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                    // Post notification of received message.
                    //sendNotification("Received: " + extras.toString());
                    sendNotification(msg);
                    Log.i(TAG, "Received: " + extras.toString());
                }
            }
         GcmBroadcastReceiver.completeWakefulIntent(intent);
    }
    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);


        Intent myintent = new Intent(this, ReceiveActivity.class);
        myintent.putExtra("message", msg);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                myintent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_stat_gcm)
        .setContentTitle("Event tracker")
        .setContentText("Events received");
    NotificationCompat.InboxStyle inboxStyle =
            new NotificationCompat.InboxStyle();
    String[] events = new String[6];
    // Sets a title for the Inbox style big view
    inboxStyle.setBigContentTitle("Event tracker details:");

    // Moves events into the big view
    for (int i=0; i < events.length; i++) {

        inboxStyle.addLine(events[i]);
    }
    // Moves the big view style object into the notification object.
    mBuilder.setStyle(inboxStyle);


        AudioManager am = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);

        /* Even if the mode is set to "Sound & Vibration" in the phone, 
         * the status code that getRingerMode() returns is RINGER_MODE_NORMAL.
         */
        switch (am.getRingerMode()) 
        {
            case AudioManager.RINGER_MODE_VIBRATE:
                mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
                break;
            case AudioManager.RINGER_MODE_NORMAL:
                mBuilder.setDefaults(Notification.DEFAULT_SOUND);
                break;
            default:
                mBuilder.setDefaults(Notification.DEFAULT_SOUND);
         }


        mBuilder.setContentIntent(contentIntent);

      mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());



    }
    public void CancelNotification(Context ctx) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) ctx
                .getSystemService(ns);
        nMgr.cancel(NOTIFICATION_ID);
    }

  }

我的接收代码

   TextView name;
    TextView deal;
    TextView valid;
    TextView address;
    JSONObject json;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_receive);
    Intent intent = getIntent();

    name = (TextView) findViewById(R.id.name);
    deal = (TextView) findViewById(R.id.deal);
    valid = (TextView) findViewById(R.id.valid);
    address = (TextView)findViewById(R.id.address);
    String message = intent.getExtras().getString("message");
    try {
        json = new JSONObject(message);
        String stime = json.getString("name");
        name.setText(stime);

        String slecturename = json.getString("deal");
        deal.setText(slecturename);

        String sroom = json.getString("valid");
        valid.setText(sroom);

        String sfaculty = json.getString("address");
        address.setText(sfaculty);


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

      }
    @Override
   protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    GcmIntentService serv = new GcmIntentService();
    serv.CancelNotification(getApplicationContext());
  }

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.receive, menu);
    return true;
   }
  }

【问题讨论】:

  • 在mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build())之后增加NOTIFICATION_ID;此声明@Durga
  • 你写得像 mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); NOTIFICATION_ID++;
  • 但显示上次通知数据相同的数据
  • 对于唯一的 NOTIFICATION_ID 使用 System.currentTimeMillis() 像 mNotificationManager.notify(System.currentTimeMillis(), mBuilder.build());检查一下。
  • 谢谢你,但它不工作

标签: android google-cloud-messaging android-json


【解决方案1】:

每个通知都必须有唯一的 ID,因此如果您希望它显示为新通知,您必须更改每个通知的 NOTIFICATION_ID。

【讨论】:

  • 是的,我写得像 mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); NOTIFICATION_ID++;
【解决方案2】:

如下更改您的代码:

private void sendNotification(String msg)
{
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent myintent = new Intent(this, ReceiveActivity.class);
    myintent.putExtra("message", msg);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, myintent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_stat_gcm)
            .setContentTitle("Event tracker").setContentText("Events received");
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    String[] events = new String[6];
    // Sets a title for the Inbox style big view
    inboxStyle.setBigContentTitle("Event tracker details:");

    // Moves events into the big view
    for (int i = 0; i < events.length; i++)
    {

        inboxStyle.addLine(events[i]);
    }
    // Moves the big view style object into the notification object.
    mBuilder.setStyle(inboxStyle);

    AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

    /* Even if the mode is set to "Sound & Vibration" in the phone, 
     * the status code that getRingerMode() returns is RINGER_MODE_NORMAL.
     */
    switch (am.getRingerMode())
    {
    case AudioManager.RINGER_MODE_VIBRATE:
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
        break;
    case AudioManager.RINGER_MODE_NORMAL:
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        break;
    default:
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
    }

    mBuilder.setContentIntent(contentIntent);

    // create new notification id
    Date date = new Date();
    NOTIFICATION_ID = (int) date.getTime();

    //now you can notify with newly created notification id
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

}

public void CancelNotification(Context ctx)
{
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
    nMgr.cancelAll();
}

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多