2016-09-23 174 views
1

我正在使用fcm在我的應用中發送通知。我想在用戶點擊通知時啓動MsgViewActivity。現在,當應用程序處於前臺,但是當應用程序未運行時,這工作得很好,只需將我帶入主要活動即可。另外請注意,我正在使用數據消息,因此即使在後臺也調用onMessageRecived。無法從FCM服務啓動活動

這裏是我的FirebaseMessagingService.class

public class FirebaseMessagingSer extends FirebaseMessagingService { 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 

     Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher); 

     Intent intent = new Intent(this, MsgViewActivity.class); 
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); 

     if(remoteMessage.getData().size()>0) { 
      String id = remoteMessage.getData().get("id"); 
      Bundle bundle = new Bundle(); 
      bundle.putString("id",id); 
      intent.putExtras(bundle); 
     } 
     PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); 
     notificationBuilder.setContentTitle("FCM NOTIFICATION"); 
     notificationBuilder.setContentText(remoteMessage.getNotification().getBody()); 
     notificationBuilder.setSmallIcon(R.mipmap.ic_launcher); 
     notificationBuilder.setLargeIcon(bmp); 
     notificationBuilder.setAutoCancel(true); 
     notificationBuilder.setContentIntent(pendingIntent); 

     NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationManager.notify(0,notificationBuilder.build()); 


    } 
} 

回答

1

從您的示例代碼使用的是消息既notification: {..}data: {..}有效載荷。

這意味着您的郵件被認爲是notification-message,因此方法onMessageReceived()僅在應用程序處於前臺時執行。 (這說明您的問題)

有兩種解決方法:只

  1. 使用數據電文。請勿在通知中發送任何內容:{..}部分消息。您可以將主體和標題設置爲數據有效負載中的附加鍵值。

  2. 您可以使用帶參數click_action =「intent_to_activity2」的通知消息。
    您還需要將意圖過濾器添加到您的活動清單。