我正在尝试呈现一个由不在正常应用程序流程中的特殊 Activity 处理的通知,并尝试让返回堆栈处理“正确”,意思是:
- 如果在应用程序运行时处理通知,则通知 Activity 应出现在当前堆栈中,从通知返回应该让我们离开我们在应用程序中的位置。请注意,这可能意味着应用程序已打开。
- 如果在应用程序未运行时处理通知,则通知 Activity 应出现在应用程序的主要(初始) Activity 中。
到目前为止,我用来显示通知的代码是:
/**
* Show (or update) a notification for the current message set.
*
* @param showNotification true to use a high priority notification which will be immediately
* displayed (as opposed to just added to the status bar)
*/
private void createOrUpdateNotification(boolean showNotification) {
Message oldest = messages.get(0);
Message newest = messages.get(messages.size() - 1);
// Create the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
// Set notification data and appearance
.setContentTitle(title)
.setContentText(newest.message)
.setSmallIcon(smallIcon)
.setWhen(newest.when)
.setColor(ContextCompat.getColor(context, R.color.primary_color))
// Set notification options
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(showNotification ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_LOW)
.setDefaults(NotificationCompat.DEFAULT_VIBRATE)
.setOnlyAlertOnce(!showNotification);
// Set up the action if the first (oldest) message has an intent builder
if(oldest.intent != null) {
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context.getApplicationContext());
stackBuilder.addNextIntent(oldest.intent);
builder.setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
}
NotificationManagerCompat.from(context).notify(notificationId, builder.build());
Log.i("notification created");
}
需要说明的是,Message.intent
是一个单一的 Intent ,配置为打开通知处理 Activity 。
我的问题是,如果应用程序当前正在运行并在打开通知时处于打开状态,则应用程序将关闭并且通知会出现在空堆栈上,并且应用程序的返回堆栈将被清除。
我的理解是,如果内容 Intent 是一个包含单个 Intent 的未决 Intent ,那么期望的行为应该是自动的,这里就是这种情况。
我错过了什么?
最佳答案
TaskStackBuilder.create 将启动一个新的任务堆栈。
改为像这样设置内容 Intent :
builder.setContentIntent(
PendingIntent.getActivity(
context,
0,
oldest.intent,
PendingIntent.FLAG_UPDATE_CURRENT
));
关于android - 如何通过通知保持返回堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41349427/