问题描述
我正在寻找一种存储变量的状态的方法,这些变量的状态可能已从初始变量(通过用户激活函数或其他方式)通过通过 onDestroy( )事件,这样,即使我打开和关闭手机,我的应用也不会重置变量.
I'm looking for a way to store the state of my variables that may have been changed from there initiation variable (ever by user activating a function or other) through the onDestroy() event so that if i turn my phone on and off my app hasn't reset the variables.
推荐答案
首先,这是来自android参考:注意:不要指望onDestroy方法被称为保存数据的地方!例如,如果活动是在内容提供者中编辑数据,这些编辑应在onPause()或onSaveInstanceState(Bundle)中提交
First of all, this is from android reference: "Note: do not count on onDestroy 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)"
要保存变量,可以按照SharedPreferences之前的说明使用.
For saving variables you can use as said before SharedPreferences.
使用内部活动类的示例:
Example for using inside activity class:
SharedPreferences prefs = getSharedPreferences("preference_file_name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("variable_key", variable);
editor.commit();
对于方法onSaveInstanceState(Bundle),只需使用Bungle参数保存变量
For method onSaveInstanceState(Bundle) just use Bungle argument to save variables
这篇关于通过onDestroy()事件存储变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!