2016-05-06 63 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.我認爲上面的代碼將爲你工作