现象:安卓应用,通过安卓自带的程序安装器安装完成以后,点击“打开按钮”,打开程序后,点击手机home键返回桌面,再次点击桌面应用图标打开应用,观察现象--应用重启,应用入口activity重新启动。
分析:通过程序安装器打开应用的方式与桌面图标打开应用的方式是有区别的。具体差别为,通过程序安装器打开应用,安卓启动应用的时候,会有一个setPackage的行为,因为这个setPackage的行为,会导致最后应用入口activity打开的时候,会传值一个FLAG_ACTIVITY_BROUGHT_TO_FRONT过来,导致应用的程序栈发生改变,从而导致后续现象的发生。
FLAG_ACTIVITY_BROUGHT_TO_FRONT官方描述如下:
If, when starting the activity, there is already a task running that starts with this activity, then instead of starting a new instance the current task is brought to the front. The existing instance will receive a call to Activity.onNewIntent() with the new Intent that is being started, and with the Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT flag set. This is a superset of the singleTop mode, where if there is already an instance of the activity being started at the top of the stack, it will receive the Intent as described there (without the FLAG_ACTIVITY_BROUGHT_TO_FRONT flag set). See the Tasks and Back Stack document for more details about tasks.
注意黑色字体。这就是造成该现象发生的关键点。
解决方法如下图:
增加flag判断
that's all-------------------------------------------------------------------------------------------------------------------------------