简体   繁体   English

当Android销毁活动以节省内存但不杀死App时,是否总是调用onDestroy?

[英]Is onDestroy always called when android destroys activity to save memory but does not kill App?

I want to use Application.ActivityLifecycleCallbacks to monitor how many activities are there in the back-stack. 我想使用Application.ActivityLifecycleCallbacks来监视后堆栈中有多少个活动。 Can I increment/decrement counter in onCreate/onDestroy to handle this? 我可以在onCreate / onDestroy中增加/减少计数器来处理吗?

onDestroy is NOT guaranteed to be called every time an activity is destroyed. 保证每次活动销毁时都会调用onDestroy。

If the user clicks back to destroy it, onDestroy will be called. 如果用户单击以销毁它,则将调用onDestroy。
If the user swipes the application from the recent app menu, onDestroy will NOT be called. 如果用户从最近的应用程序菜单中滑动应用程序,则不会调用onDestroy。
If the application crashes, it's undetermined if it'll be called (from my experience, it isn't called). 如果应用程序崩溃,则无法确定它是否会被调用(根据我的经验,它没有被调用)。

onDestroy() is the final method that is called on an Activity instance before it's destroyed and completely removed from memory. onDestroy()是在Activity实例销毁并从内存中完全删除之前对其进行调用的最终方法。 In extreme situations Android may kill the application process that is hosting the Activity, which will result in OnDestroy not being invoked. 在极端情况下,Android可能会终止托管Activity的应用程序进程,这将导致无法调用OnDestroy。 Apparently most of the Activities will not implement this method because most clean up and shut down has been done in the OnPause and OnStop methods. 显然,大多数活动都不会实现此方法,因为大多数清理和关闭操作都是通过OnPause和OnStop方法完成的。 For more details please visit Android Developers Portal. 有关更多详细信息,请访问Android Developers Portal。 ( https://developer.android.com/reference/android/app/Activity.html "Android Developers") https://developer.android.com/reference/android/app/Activity.html “ Android开发人员”)

Is onDestroy always called when android destroys activity to save memory? 当Android销毁活动以节省内存时,是否总是调用onDestroy?

Yes

Documentation: 文档:

The final call you receive before your activity is destroyed. 活动销毁之前收到的最后一个电话。 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()方法区分这两种情况。

I want to use Application.ActivityLifecycleCallbacks to monitor how many activities are there in the back-stack. 我想使用Application.ActivityLifecycleCallbacks来监视后堆栈中有多少个活动。 Can I increment/decrement counter in onCreate/onDestroy to handle this? 我可以在onCreate / onDestroy中增加/减少计数器来处理吗?

Better to counter in the onStart() and onStop() methods, onCreate() doesn't guarantee visibility. 最好用onStart()onStop()方法来应对,onCreate()不能保证可见性。 For example if somehow something stopped onStart() from happening. 例如,如果某种原因阻止了onStart()的发生。

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

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