通过单击启动器中的应用程序图标启动一个 Activity ,应该将该 Activity 带到前台,就像从历史记录中选择它一样。因此不应存在 onCreate 调用。
但是,如果我们在通过单击通知启动 Activity 后尝试执行此操作,则启动器只会启动 Activity 的另一个实例。
我必须添加什么标志才能使启动器继续按预期工作(从后台恢复应用程序的确切状态)?
我会发布基本代码。
这将启动通知:
Intent resumeIntent = new Intent(this, MainActivity.class);
PendingIntent resumePendingIntent = PendingIntent.getActivity(this, 2,
resumeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification resumeNotification = new Notification.Builder(this).setContentTitle(
"Resume style")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(resumePendingIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
notificationManager.notify(1, launcherNotification);
这是 list Activity 的样子:
<activity
android:name="com.example.ihatenotifiicationsapp.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
此resumeIntent 将由Android 自动添加到FLAG_ACTIVITY_NEW_TASK。此标志将允许从后台恢复应用程序(如果存在)。
到这里为止一切都很好,但是,如果在您单击此通知并恢复该应用程序后,您从启动器中单击该应用程序,然后 Android 将启动 MainActivity 的另一个实例。
这会破坏我的应用程序和后台堆栈(您将在堆栈中有 2 个 MainActivity,这对用户来说很奇怪)。
有趣的是只有在您单击通知后才会发生这种情况(单击启动器行为以启动另一个实例)。
最佳答案
如果您想要这种行为,您可以在 activity
标记中使用标记 android:launchMode="singleTask"
。如果当前有一个 Activity 实例,这将阻止操作系统启动任何其他实例。有关启动行为的更多信息,请参阅 SDK Doku here
我根据下面的 Emanuel Moecklin 评论编辑了这个答案。混合了 lauchModes。
摘自独库:
The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one.
关于Android 单击启动器图标仅在从通知启动该 Activity 后发出时才会启动新 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19518296/