Android Studio运行app,按HOME键回到桌面,再次点击app图标启动再次打开启动页面解决方案

背景
  • 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
        }
    }
}
参考文档

中文 中文2
英文 英文2

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值