2015-12-21 97 views
1

我開發與GCM推送通知的Android應用程序,其中每當打開通知它清除從堆棧中的所有活動的頁面清除所有活動。如何防止通知從堆棧中

Intent intent = new Intent(this, MainActivity.class); 
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 
stackBuilder.addParentStack(MainActivity.class); 
stackBuilder.addNextIntent(intent); 
long[] vibrate = {0, 100, 200, 300}; 
Uri notification = RingtoneManager 
     .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
PendingIntent contentIntent = stackBuilder.getPendingIntent(0, 
     PendingIntent.FLAG_UPDATE_CURRENT 
       | PendingIntent.FLAG_ONE_SHOT); 
Bitmap largIcon = BitmapFactory.decodeResource(this.getResources(), 
     R.mipmap.ic_launcher); 
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
     this).setSmallIcon(R.mipmap.small_icon_notification) 
     .setContentTitle(getResources().getString(R.string.app_name)) 
     .setLargeIcon(largIcon) 
     .setSound(notification) 
     .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) 
     .setContentText(msg).  setSound(notification) 
     .setStyle((new NotificationCompat.BigTextStyle()).bigText(msg)) .setAutoCancel(true); 
mBuilder.setVibrate(vibrate); 
mBuilder.setContentIntent(contentIntent); 
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build()); 
+0

你定義在你的清單中的父母?像這樣的android:parentActivityName =「MainActivity」如果不添加此行並測試您的代碼,它將正常工作 –

+0

嘗試刪除autocancel – Nisarg

回答

0

要防止通知清除backstack中的所有活動,必須設置特殊活動PendingIntent。一個特殊的Activity不需要返回堆棧。使用清單來設置活動任務選項並通過調用getActivity()來創建PendingIntent。

一個的PendingIntent指定要採取的動作在未來。它允許您將未來意向傳遞給另一個應用程序,並允許該應用程序執行該意圖,就好像它具有與您的應用程序相同的權限,無論您的應用程序是否仍然在意圖最終被調用的時間點附近

通過給PendingIntent到另一個應用程序,您授予它執行您指定的操作的權限,就好像另一個應用程序是您自己的一樣(具有相同的權限和標識)。

下面的代碼片段演示過程:

// Instantiate a Builder object. 
NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 

// Creates an Intent for the Activity 
Intent notifyIntent = 
    new Intent(new ComponentName(this, ResultActivity.class)); 

// Sets the Activity to start in a new, empty task 
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
    Intent.FLAG_ACTIVITY_CLEAR_TASK); 

// Creates the PendingIntent 
PendingIntent notifyIntent = PendingIntent.getActivity(this,0,notifyIntent,PendingIntent.FLAG_UPDATE_CURRENT); 

// Puts the PendingIntent into the notification builder 
builder.setContentIntent(notifyIntent); 

// Notifications are issued by sending them to the 
// NotificationManager system service. 
NotificationManager mNotificationManager = 
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

// Builds an anonymous Notification object from the builder, and 
// passes it to the NotificationManager 
mNotificationManager.notify(id, builder.build()); 

以下是如何設置特定活動的PendingIntent一個有用的鏈接: http://developer.android.com/training/notify-user/navigation.html