android如何使用onTerminate()方法? [英] How to use onTerminate() method , android?

查看:173
本文介绍了android如何使用onTerminate()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 SharedPreferences 保存一些变量.在我的 onCreate()方法中,我使用 SharedPreferences 初始化变量,并且我希望在应用程序结束时存储此变量.我将此代码放在 onTerminate()方法上,但从未存储过变量.我认为从未调用过 onTerminate()方法,因为我还看到对此方法的评论,说//不保证被调用.那么,如何在停止应用程序之前保存变量的状态?我知道如何,只是不知道将代码放置在何处.

I am trying to save some variables using SharedPreferences. In my onCreate() method I initialize my variables using SharedPreferences , and I want when the application ends to store this variables. I am putting this code on the onTerminate() method but the variables are never stored. I think that the onTerminate() method is never called , as i also see a comment on this method saying // not guaranteed to be called . So how can i save the state of my variable just before I stop the application? I know how , I just don't know where to place my code.

推荐答案

实际上,为了安全起见,应将内容保存在onPause()中,因为(至少在3.0之前)您的进程可以在调用后被OS杀死onPause().这意味着onStop()和onDestroy()可能会被调用,也可能不会被调用.

Actually, to be safe, you should save things in onPause() because (at least pre-3.0) your process can be killed by the OS after it calls onPause(). This implies that onStop() and onDestroy() may or may not be called.

在任何情况下,都不能保证onDestroy()会被调用.如果操作系统决定终止您的进程,则无需在任何活动上调用onDestroy().

In any case, there is no guarantee that onDestroy() will ever be called. If the OS decides to kill your process it won't bother calling onDestroy() on any activities.

这篇关于android如何使用onTerminate()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆