背景
- app有一个启动页面MainActivity,还有其他的页面OtherActivity(是通过启动页中按钮点击跳转过来的)
- MainActivity的启动模式为
android:launchMode="singleTask"
AndroidManifest.xml文件:
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OtherActivity" />
流程
- 运行app
- 进入启动页MainActivity
- 点击按钮启动OtherActivity
- 按HOME键回到桌面
- 点击app图标启动
理想的结果是启动app之后界面停留在OtherActivity界面,但是实际上还会重新进入启动界面MainActivity。像一些存在登录界面为启动页面的app,就会出现只要按HOME键就需要重新到登录界面,体验不是很友好。
原因
首先排除系统杀死app进程的原因,因为按HOME键之后通过进程按键是可以启动app,并且还原到按HOME键时的界面。
Android Studio运行启动app的Intent(包含第三方启动应用)和点击app图标启动的Intent内容是不一样的。
解决方案
第一种:
在启动页的onCreate()
方法中setContentView
之前添加如下代码:
if (null != intent && intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
finish()
return
}
有些手机设备上第一种方案可能会无效。
第二种:
if (!this.isTaskRoot) {
// 判断当前activity是不是所在任务栈的根
if (intent != null) {
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN == intent.action) {
finish()
return
}
}
}