2014-02-26 39 views
0

我有一個應用程序使用正在進行的通知讓用戶知道其正在運行。這很方便,因爲它需要在後臺一直運行以接收消息。該應用程序主要由一個活動與許多片段和一對服務組成。從正在進行的通知中啓動活動第二次崩潰

這是我用來顯示和更新通知的方法。它在一個名爲Notifications.java的類中實現。 它的方法在MainActivity的onResume中以及接收消息的服務中調用。

public static void updateOngoingNotification(Context c, String text) { 
    Intent intent = new Intent(c, MainActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    PendingIntent pIntent = PendingIntent.getActivity(c, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(c) 
      .setSmallIcon(R.drawable.ic_launcher) 
      .setOngoing(true) 
      .setContentText(text) 
      .setContentTitle(c.getString(R.string.app_name)) 
      .setContentIntent(pIntent); 

    NotificationManager notificationManager = (NotificationManager) c 
      .getSystemService(c.NOTIFICATION_SERVICE); 
    notificationManager.notify(0, mBuilder.build()); 
} 

的問題是,這一切似乎工作,因爲它應該,但是當我嘗試啓動活動第二次,應用程序凍結。我懷疑通知ID或丟失的標誌,但迄今沒有找到解決方案的運氣。

+0

它是否崩潰或你得到任何日誌? –

回答

2

當你的活動是singleTop或者您在IntentFLAG_ACTIVITY_SINGLE_TOP標誌調用它,新Intent對象將被傳遞到您的活動的onNewIntent方法,如果它已經在運行。因此,您需要在您的活動中覆蓋onNewIntent方法,該方法將從通知中接收新的Intent對象。所以,你可以相應地更新你的活動。

Ref:http://developer.android.com/intl/es/reference/android/app/Activity.html#onNewIntent(android.content.Intent)

+0

謝謝你的快速回答。它的工作,但我不得不將標誌設置爲\t \t intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); 這不是我上面發佈的代碼的一部分。不過,這個解決方案對我的應用程序很有用。謝謝! :) – Alex

+0

很高興幫助你:) –

相關問題