同一个应用不同activity显示在多任务
同一个App中的不同Activity显示在多任务,类似微信小程序、快应用。

1、启动方式
有两种方式实现启动同一个应用中的Activity也能出现在最近任务列表:
1.1、启动时添加Flag
页面跳转的时候增加Flag:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
FLAG_ACTIVITY_NEW_DOCUMENT:此标志用于将文档打开到一个 基于此意图的新任务中;
FLAG_ACTIVITY_MULTIPLE_TASK:此标志用于创建新任务并将活动导入其中。
1.2、在manifest里配置
在AndroidManifest.xml里配置要跳转的Activity属性,对于除 none 和 never 以外的值,必须使用 launchMode="standard" 定义 Activity。如果未指定此属性,则使用documentLaunchMode="none"。
<activity
android:name=".XXActivity"
android:documentLaunchMode="intoExisting"
android:excludeFromRecents="false" //默认
android:maxRecents="3"/>
①documentLaunchMode(启动模式):
intoExisting:如果之前已经打开过,则会打开之前的(类似于Activity的singleTask)
always:不管之前有没有打开,都新创建一个(类似于Activity的standard)
none:不会在任务列表创建新的窗口,依旧显示单个任务
never:不会在任务列表创建新的窗口,依旧显示单个任务,设置此值会替代 FLAG_ACTIVITY_NEW_DOCUMENT 和FLAG_ACTIVITY_MULTIPLE_TASK 标志的行为(如果在 Intent 中设置了其中一个标志)
②excludeFromRecents:默认为false。设置为true时,只要离开了这个页面,它就会从最近任务列表里移除掉。效果同FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS。
③maxRecents:设置为整型值,设置应用能够包括在概览屏幕中的最大任务数。默认值为16。达到最大任务数后,最近最少使用的任务将从概览屏幕中移除。 android:maxRecents 的最大值为50(内存不足的设备上为 25);小于 1 的值无效。
2、配置图标和名称
配置Activity在最近任务列表里的标题和图标。
private String mLabel;
@Nullable
private Icon mIcon;
2.1、manifest配置
在AndroidManifest.xml中给要显示的Activity设置android:icon和android:lable,这种方法是可行的,但相当于是写死固定了,缺乏灵活性。
<activity
android:label="@string/label"
android:icon="@drawable/icon"
android:name=".ui.view.ui.faker.PhoneInfoActivity"
android:exported="false" />
2.2、代码设置
通过setTaskDescription(ActivityManager.TaskDescription taskDescription)方法可以设置描述包含此Activity的任务栈的信息,以便在系统最近任务中显示:
setTaskDescription(new ActivityManager.TaskDescription("跳一跳"));
还可以设置图标Icon,传入需要设置的Bitmap即可:
description = ActivityManager.TaskDescription(label, bitmap)
构造方法中会将传入的Bitmap转换成Icon:
/**
* Create an Icon pointing to a bitmap in memory.
* @param bits A valid {@link android.graphics.Bitmap} object
*/
public static @NonNull Icon createWithBitmap(Bitmap bits) {
if (bits == null) {
throw new IllegalArgumentException("Bitmap must not be null.");
}
final Icon rep = new Icon(TYPE_BITMAP);
rep.setBitmap(bits);
return rep;
}
直接构造的方法已经被废弃,推荐TaskDescription使用中的Builder类来构造TaskDescription描述。这种方式有个缺点,Icon没办法设置成Bitmap,Icon只能指定本地资源id作为参数。
var description = ActivityManager.TaskDescription.Builder()
.setLabel(label)
.setIcon(R.drawable.app_icon_one)
.build()
设置Icon的方法已经被标记为hide,当然也可以用反射去设置成需要的Icon:
/**
* Sets the icon resource for this task description.
* @hide
*/
public void setIcon(Icon icon) {
mIcon = icon;
}