安装app后直接点击打开带来的问题

547 阅读1分钟

问题

项目发版当晚发现的:安装完APP后直接点击打开,接着Home键退到后台,再次打开App 时发现重启了。试了一下去哪儿,陌陌等几个主流app,也有这个问题

原因

The Launcher starts an app using an intent with android.intent.action.MAIN action and android.intent.category.LAUNCHER category. The installer starts an app with the android.intent.action.MAIN action and no category.

大概就是桌面启动app和安装器启动app的Intent不一样,安装完直接open其实已经启动了app,但是桌面点击图标没有认为你已经启动了app,于是重启。

解决办法

在你的app的入口Activity的onCreate()方法最开始加入代码段:

if (!this.isTaskRoot()) { //判断该Activity是不是任务空间的源Activity,false也就是说是被系统重新实例化出来
                //如果你就放在launcher Activity中话,这里可以直接return了
                Intent mainIntent = getIntent();
                String action = mainIntent.getAction();
                if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)) {
                    finish();
                    return;//finish()之后该活动会继续执行后面的代码,加return避免可能的exception
                }
            }