【发布时间】:2014-12-23 02:05:52
【问题描述】:
我有一个 Activity,其 launchMode 为 singleTop(在清单中)。我的理解是,如果 Activity 是 singleTop 并且它位于 Activity 堆栈的顶部,那么使用新 Intent 启动 Activity 实际上会导致在 Activity 上调用 onNewIntent() ,而不会创建新的 Activity 实例(因此,不会调用 onCreate())。
此 Activity 运行一个显示持续通知的前台服务。选中后,此通知只会将用户带回到堆栈顶部的 Activity(没有从这个 singleTop 活动启动的活动)。 My problem is that when the notification is selected, sometimes a new instance of the Activity is created – even when it is visibly already on top of the stack.这对我的 Activity 来说是有问题的,因为它的行为对于它在后台被杀死并重新启动的情况是不同的(与刚刚使用 onNewIntent() 放在前面的情况相比)。我的服务用于呈现通知的代码如下:
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
Intent notificationIntent = new Intent(this, MyProblematicActivity.class);
notificationIntent.putExtra(EXTRA_MY_DATA, "MyData");
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder notificationBuilder = new Notification.Builder(getApplicationContext()).
setSmallIcon(smallIconResourceId).
setContentTitle(contentTitle).
setContentText(contentText).
setAutoCancel(false).
setOngoing(true).
setContentIntent(pendingIntent);
startForeground(MY_NOTIF_ID, notificationBuilder.build());
我说这种行为有时会发生,当它发生时,它会反复发生。例如:
- MyProblematicActivity 首次启动
- 服务启动并显示通知
- 已选择通知。
- MyProblematicActivity 再次创建(服务已启动,通知已显示)。
- 重复 2-4 次。
有时,在 #3 之后,调用 MyProblematicActivity 的 onNewIntent() 而不创建新实例,并且事情按预期工作。
我不知道为什么会发生这种情况。任务根目录下的状态活动是否会对我的 singleTop 活动的行为方式产生任何影响? FWIW,创建 MyProblematicActivity 的 Activity 是一个 singleTask Activity。
【问题讨论】:
-
你终于找到问题和解决方案了吗?
标签: android android-pendingintent launchmode taskstackbuilder