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:

<activity
    android: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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值