5

我有GCM通知實施。我知道客戶端應用程序收到的通知是處於前景,背景還是死亡狀態。我想知道的是,當應用程序處於死亡狀態時,如何啓動收到通知的應用程序?當收到GCM通知時啓動應用程序

回答

5

在郵件接收器,我請執行下列操作:

final Intent notificationIntent = new Intent(context, YourActivity.class); 
notificationIntent.setAction(Intent.ACTION_MAIN); 
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER); 

這裏與入門活性更換YourActivity.class。這對我有效。

+2

如果應用程序已經運行,該怎麼辦? – Ahmed

+0

如果應用程序從任務列表中刪除,該怎麼辦?在這種情況下,「消息接收者」將不會被調用。它將按系統處理,並由「click_action」標籤點擊。但是我的擔心是在通知到達後打開我的目標活動。 –

+0

如何在fcm消息中獲取上下文? –

2

您可以使用NotificationManager啓動您的活動。

嘗試下面的代碼裏面使用您的的onMessage()方法這是重載方法在擴展GCMBaseIntentService類GCM的類。

int icon = R.drawable.your_app_icon; 
     long when = System.currentTimeMillis(); 
     NotificationManager notificationManager = (NotificationManager) context 
       .getSystemService(Context.NOTIFICATION_SERVICE); 
     Notification notification = new Notification(icon, message, when); 
     String title = context.getString(R.string.app_name); 

     Intent notificationIntent = new Intent(context, YOUR_ACTIVITY.class); 
     notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     // notificationIntent.putExtra("PostName", vPostText); 
     // Log.i(TAG, "Sent Postid " + postid); 

     // Util util = (Util) context.getApplicationContext(); 
     // util.setPostID(postid); 
     // util.setNotify(true); 
     // util.setUserNAME(vPortCode); 
     // util.setPostNAME(vPostText); 
     // util.setmEDIA(vMedia); 
     // util.setmEDIATHHUMB(vMediaThumb); 
     // util.setmEDIATYPE(vMediaType); 
     // util.setAirportName(vAirportName); 

     notificationIntent.putExtra("Set_image", true); 
     notificationIntent.putExtra("Notify", true); 

     // set intent so it does not start a new activity 
     // notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 
     // notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     // notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 
     // | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
     PendingIntent intent = PendingIntent.getActivity(context, 
       (int) System.nanoTime(), notificationIntent, 0); 

     notification.setLatestEventInfo(context, title, message, intent); 
     notification.defaults |= Notification.DEFAULT_SOUND; 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 
     notificationManager.notify((int) System.nanoTime(), notification); 
+1

謝謝。我知道如何從應用程序開始一個活動。但是,我想要做的是,收到通知後,如果我的應用程序在後臺,我會將其帶到前臺, 如果它在前臺,那麼我將繼續處理,並且如果我的應用程序處於停止/死亡狀態,然後我想「重新啓動應用程序」而不是活動。 那麼你能告訴我,當應用程序處於收到通知的停止/死亡狀態時,是否有任何方式啓動應用程序? – jasdmystery

+0

@jasdmystery:你找到了嗎?我面臨同樣的問題。 – user836026

+1

請參閱上面的答案。 – jasdmystery

相關問題