简体   繁体   English

按下主页按钮时活动被破坏

[英]Activity is getting destroyed while pressing the home button

In my application, when I press the home button the activity is going to onDestroy() .在我的应用程序中,当我按下主页按钮时,活动将转到onDestroy() It suppose to be called onPause() method only right?它假设只被调用onPause()方法对吗?

Why it is happening so?为什么会这样?

also check that you don't use the android:noHistory flag in your manifest for the Activity还要检查您的清单中是否没有为 Activity 使用 android:noHistory 标志

documentation: android:noHistory Whether or not the activity should be removed from the activity stack and finished (its finish() method called) when the user navigates away from it and it's no longer visible on screen文档:android:noHistory 当用户离开它并且它在屏幕上不再可见时,是否应该从活动堆栈中删除该活动并完成(调用它的 finish() 方法)

It depends on how much memory your phone has, if your phone does not have very much memory, then it will destroy the activity to free up resources immediately.这取决于你的手机有多少内存,如果你的手机没有太多内存,那么它会立即破坏活动以释放资源。 On new phones, this will not happen because they have plenty of spare memory.在新手机上,这不会发生,因为它们有足够的备用内存。

You activity could be destroyed upon pressing the home button if the system is constrained and has determined it needs to free some resources.如果系统受到限制并确定需要释放一些资源,则您的活动可能会在按下主页按钮时被破坏。 The documentation states that onDestroy() can be called if: 文档指出,在以下情况下可以调用onDestroy()

This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.这可能是因为活动正在完成(有人在其上调用了 finish() ,或者因为系统暂时销毁了该活动的实例以节省空间)。您可以使用 isFinishing() 方法区分这两种情况。

Additionally, do note that the system can kill your program without calling onDestroy() after onStop() has been called.此外,做笔记,该系统可以kill你的程序,而无需调用onDestroy()onStop()被调用。 Therefore, any cleanup/data persistence code should be in either onPause() or onStop() .因此,任何清理/数据持久性代码都应该在onPause()onStop()

Well, it depends on a lot of factors.嗯,这取决于很多因素。 If you are facing this issue on Android 3.2+ devices, you should add screenSize property to android:configChanges如果您在 Android 3.2+ 设备上遇到此问题,您应该将 screenSize 属性添加到 android:configChanges

    android:configChanges="keyboardHidden|orientation|screenSize"

Besides, also add android:launchMode="singleTop" to your launcher activity.此外,还将 android:launchMode="singleTop" 添加到您的启动器活动中。 Do note that you'd need to use Android SDK 15 or above as target, however, your app will work on older devices as well.请注意,您需要使用 Android SDK 15 或更高版本作为目标,但是,您的应用程序也可以在旧设备上运行。 Hope this helps.希望这可以帮助。

要检查的另一件事是您的活动是否在onPause()时调用了finish() onPause()

当然可能是内存问题,但在此之前检查清单文件,在活动的声明中,如果您声明了“无历史记录”(您不希望活动保留在活动堆栈中。您也可以使用一些当您创建具有意图的活动时标记。那么,最有可能的答案是 Alex Contour 给出的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM