2016-05-06 64 views
0

我想这很难通过阅读这个问题的标题来解释。我正在编写一个应用程序,它可以将已知服务器发送给GCM的环境因素警报(温度等)发送给GCM,然后GCM将其发回给手机。整个GCM运作良好。问题出现在通知到达时。当发生警报(触发)时,它被认为发送通知给手机。然后点击警报启动活动以显示警报。这是可以的,但是如果等待被点击时有2个或更多的警报,它将只处理一个,忽略其余(“mensaje”)。这是我在延伸extends GcmListenerService的类中的通知内容。如何处理GCM通知,启动每个提醒的活动而不删除其他提醒

public static void showAlerts(Context context, String mensaje) 
{ 
    Intent notificationIntent = new Intent(context.getApplicationContext(), MainActivity.class); 
    notificationIntent.putExtra("mensaje", mensaje); 
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP 
      | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
    Random r = new Random(); 

    PendingIntent pendingIntent = PendingIntent.getActivity(context, r.nextInt(), 
      notificationIntent, 0); 
    NotificationManager notificationManager = (NotificationManager) context 
      .getSystemService(Context.NOTIFICATION_SERVICE); 

    Notification notification = new NotificationCompat.Builder(context) 
      .setContentTitle(context.getString(R.string.app_name)) 
      .setContentText("Nueva alerta recibida") 
      .setSmallIcon(R.drawable.termometrorojo) 
      .setNumber(UtilidadesGCM.num_notificaciones++) 
      .setOnlyAlertOnce(true) 
      .setContentIntent(pendingIntent) 
      .setWhen(System.currentTimeMillis()) 
      .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) 
      .setDefaults(Notification.DEFAULT_LIGHTS) 
      .setAutoCancel(true).build(); 

    notificationManager.notify(0, notification); 
} 

然后在MainActivity,我的代码来处理此,并打开活动显示警报

private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     String nuevaAlerta = intent.getExtras().getString("mensaje"); 
     procesaAlerta(nuevaAlerta); 

     //mDisplay.append(nuevaAlerta + "\n"); 
    } 
}; 



public void procesaAlerta (String alerta) 
{ 
    Intent intent = new Intent(this, Alertas.class); 
    intent.putExtra("mensaje" , alerta); 
    startActivity(intent); 
} 

的Alertas类将解析消息罚款,并在其活动显示,但只会这样做一次。如果有多于两个警报被读取,它只会处理一个。如果有的话,它工作正常。对不起,如果我没有更好解释,但很难不显示所有的代码。 谢谢!

回答

1

尝试写这行

notificationManager.notify(new Random().nextInt(), notification); 

代替

notificationManager.notify(0, notification); 

你通知的id是每一个同时让你最后的通知才有效。每个新的通知ID都由ID 0替换。所以我使用随机ID而不是固定ID 0.我认为上面的代码将为你工作