java – 如何在Android应用关闭或失去焦点时调用方法?

因为我正在构建的应用程序将处理相当敏感的数据,所以我希望每次用户登录时都将SQLite数据库与服务器同步,并在每次应用程序失去焦点时删除emty数据库(因为用户移动到主屏幕或另一个应用).

看到the Activity lifecycle,我的想法是通过清空每个Activity的onDestroy中的数据库来做到这一点.为了测试所描述的生命周期,我只是覆盖所有生命周期方法(onCreate,onStart,onResume,onPause,onStop和onDestroy),在其中包含一些日志消息,并启动我的应用程序.

日志消息包含在我的SettingsActivity中.当我进入我的应用程序并移动到设置时,它运行onCreate,onStart和onResume(如预期的那样).然后,当我单击一个设置并移动到下一个屏幕时,它将在onPause和onStop上运行(仍然如预期的那样).要返回到设置屏幕,我单击后退按钮,它再次运行onStart和onResume(仍然按预期),当我现在再次单击后退按钮返回到初始屏幕时,它(令我惊讶的是)运行onPause, onStop AND onDestroy.

所以我的问题;

>为什么在应用程序未完成时会破坏活动?
>更重要的是:当应用程序关闭或失去焦点时,如何运行我的CleanUp方法?

最佳答案
您可以在此处获得更多信息:http://developer.android.com/training/basics/activity-lifecycle/stopping.html

即使我认为你已经读过因为你已经研究了活动生命周期,你可以在第一个图中看到onDestroy()在onStop()之后调用,这个调用完全由系统管理:你不应该期待任何行为.系统将决定何时调用此方法,有时,此方法永远不会被调用(参见此处:http://developer.android.com/reference/android/app/Activity.html).当系统需要内存时,您的活动将传入onStop(),仅此而已.

因此,要回答第二个问题,请阅读文档中有关onDestroy()方法的说明:

Note: do not count on this method being called as a place for saving
data!
For example, if an activity is editing data in a content
provider, those edits should be committed in either onPause() or
onSaveInstanceState(Bundle), not here. This method is usually
implemented to free resources like threads
that are associated with an
activity, so that a destroyed activity does not leave such things
around while the rest of its application is still running. There are
situations where the system will simply kill the activity’s hosting
process without calling this method (or any others) in it, so it
should not be used to do things that are intended to remain around
after the process goes away.

所以很明显,这是一个制作清理过程的好地方.所以你应该使用onPause()或onStop()方法之一.

onStop()在文档中描述如下:

Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

onPause()在文档中描述如下:

Called as part of the activity lifecycle when an activity is going
into the background, but has not (yet) been killed.
[…]
When activity B is launched in front of activity A, this callback will be
invoked on A. B will not be created until A’s onPause() returns, so be
sure to not do anything lengthy here.

[…]
In situations where the system needs more memory it may kill paused processes to reclaim resources.

我们现在知道onPause()旨在允许您保存数据,并且在执行onPause()之后,系统可能会终止您的进程.所以,在onPause()中进行清理似乎是最安全的地方,因为你很确定每次都会调用它.

此外,正如您可以阅读的那样,在这里进行清理会使您的应用程序变慢,但无论如何在每次获得/松散焦点时清理和重新创建数据库都是一个非常繁重的过程……

要恢复:在onPause()方法中执行清理过程,在onResume()中执行init过程.请记住,使用此类过程您的应用程序可能会非常慢.

希望这可以帮到你.

转载注明原文:java – 如何在Android应用关闭或失去焦点时调用方法? - 代码日志