【问题标题】:Get multiple GCM messages获取多条 GCM 消息
【发布时间】:2016-05-08 18:36:13
【问题描述】:

这个类不会处理多条GCM消息并显示在通知栏上,目前只处理一条,如何让它处理多条消息?

public class GCMIntentService extends GcmListenerService {
    private static final String TAG = "GCMIntentService";
    int notifyid = 0;

    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");
        Log.d(TAG, "from:" + from);
        Log.d(TAG, "message:" + message);
        sendNotification(message);
    }

    private void sendNotification(String message) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, notifyid, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.logo)
                .setContentTitle("New Messsage")
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSound)
                .setContentIntent(pendingIntent);
            int numMessages = 0;
            notificationBuilder.setContentText(message).setNumber(++numMessages);
            NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(notifyid, notificationBuilder.build());
        }
    }
}

【问题讨论】:

  • 由于您使用相同的通知 id 即 0,因此将生成的所有通知都是重叠的,因此您只能看到单个通知。如果你想要不同的通知,你应该使用不同的 notifyid。

标签: java android google-cloud-messaging message


【解决方案1】:

来自the documentation:

public void notify (int id, Notification notification)

发布要在状态栏中显示的通知。 如果您的应用程序已经发布了具有相同 id 的通知并且尚未取消,则它将替换为更新的信息。

notifyid 在您发布的代码中似乎永远不会改变,这就是为什么您只会看到一条通知。

【讨论】:

  • 所以我要移动 NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(notifyid, notificationBuilder.build());在这个方法里面^^^^ ???
  • 我不确定我是否理解您的评论。您需要为每次调用notify 生成不同的ID。你可以这样做,例如通过using an AtomicInteger,或通过生成随机数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多