本文主要是介绍Android APP在debug模式下,如何避免activity被系统destroy,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近在调式APP时发现,如果在APP运行时(比如:进入了某个子模块的某个列表项的详情页:InfoShowActivity),点击home按钮,返回主屏幕。然后再返回APP时,APP不会显示之前的界面(InfoShowActivity),而是会如同重新打开一般,显示主页(MainActivity)。之前的详情页会自动destroy。
更奇怪的是,点击home按钮,返回主屏幕时,Logcat中只检测到InfoShowActivity的onStop方法,并没有检测到onDestroy方法。也就是说,InfoShowActivity没有执行onDestroy方法就被destroy,然后消失了。
刚开始,我还以为是APP的内存占用过高,导致触发系统GC操作。但使用Android Studio Memory Profiler(View-Tool Windows-Profiler)进行监测,相对于我开发的其他的APP,并没有发现内存占用量有什么区别。
这时我想到,之前是debug模式下出的问题,是否可以测试一下正式安装后的情况。于是我打包APK,然后安装到手机。结果,这个问题却不再重现了!
对比之前的测试过程,只有在debug模式下才出问题;而在打包后就没问题了。我猜测,是否系统对于APP的处理方式,在debug模式和正式安装模式下,有所区别?
我忽然想到了Android Studio新加的Gemini助手。于是提出问题:
Why in debug mode, when press home button, then open app, the previous activity will destroy?
Gemini回答了我:原来,在debug模式下,点击home按钮时,Android系统会destroy当前的activity。这是因为系统为了我们调试方便,想要保证给我们看到的永远最新的activity,就会destroy之前的Activity。如果要避免activity被destroy,就需要在activity的配置中加入:
android:alwaysRetainTaskState="true"
折腾了几个小时,终于找到了原因。真需要感谢Gemini。
另外,这是Gemini的回复原文,供参考:
When you press the home button in debug mode, the Android system will destroy the current activity. This is because the Android system knows that you are debugging the app and it wants to make sure that you are always seeing the latest version of the app.
When you open the app again, the Android system will create a new instance of the activity. This is because the previous instance of the activity was destroyed when you pressed the home button.
This behavior is specific to debug mode. In release mode, the Android system will not destroy the current activity when you press the home button. This is because the Android system wants to preserve the user's experience.
If you want to prevent the current activity from being destroyed when you press the home button in debug mode, you can use the android:alwaysRetainTaskState attribute in your manifest file. This attribute tells the Android system to always retain the task state, even when the app is in the background.
For example, to prevent the MainActivity from being destroyed when you press the home button in debug mode, you would add the following attribute to the <activity> element for MainActivity in your manifest file:
<activityandroid:name=".MainActivity"android:alwaysRetainTaskState="true"><!-- ... -->
</activity>
However, it is important to note that using the android:alwaysRetainTaskState attribute can have a negative impact on performance. This is because the Android system will need to keep more memory in use to retain the task state. Therefore, you should only use this attribute if you are absolutely sure that you need to prevent the current activity from being destroyed.
这篇关于Android APP在debug模式下,如何避免activity被系统destroy的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!