我正在编写一个用于托管应用程序的SDK。我的SDK创建一个需要恢复应用程序的通知,就像你按下任务按钮并选择应用程序一样,或者长按Home键并选择你的应用程序。
这是我一直在努力做的:
PackageManager packageManager = context.getPackageManager();
intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 10, intent, flags);
Notification notification = new NotificationCompat.Builder(context).
setContentIntent(pendingIntent).
...
build();
getNotificationManager().notify(NOTIFICATION_ID, notification);
我在主机应用程序上测试了一个启动器活动,启动模式为"default"(在清单中没有设置启动模式),我的sdk也有一个活动,午餐模式为"singleTask"。
- 所以我午餐应用程序
- 启动我的SDK活动,它在oncreate方法中触发一个测试通知。
- 我按home
- 我点击通知。
完成这些步骤后,我希望返回到我的活动,但它打开了主机启动器活动的另一个实例。我错过了什么?我该怎么做呢?
如果你想从你暂停的地方恢复,然后删除标志"NEW_TASK"。它不会制造新的任务。
根据您的要求,主机应用程序需要在启动器活动上设置"singleTop"启动模式,并且从您的SDK中无法设置它。你需要告诉宿主应用设置这个标志。
一旦你设置了"singleTop"启动模式,你将通过重写onNewIntent()方法接收新的意图,你的活动将处于与以前相同的状态
在你的AndroidManifest.xml
文件,去你的主活动的声明和使用android:launchMode="singleTask"
像这样:
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
这样,如果任务已经在后台运行,系统将把它放在前台,让用户继续他在后台推送活动之前正在做的事情。