简体   繁体   English

在应用程序销毁时保存变量不起作用

[英]Saving variable on application destroy doesn't work

I want to save some variables after exiting activity which are set during the lifetime of my android activity and show them when I launch activity again but I don't seem to manage to get things working. 我希望在退出活动后保存一些变量,这些变量是在我的android活动的生命周期中设置的,并在我再次启动活动时显示它们,但我似乎无法让事情正常工作。 Here's how I do it: 我是这样做的:

I created an integer variable "test": 我创建了一个整数变量“test”:

public class MainActivity extends Activity {
int test = 1;

Then I write a method to change this varibale's value by pressing a button: 然后我写一个方法来通过按下按钮来改变这个varibale的值:

public void changeValueTest(View view) {
    this.test = 2;
}

Then I use onSaveInstanceState() method to save the changed value: 然后我使用onSaveInstanceState()方法来保存更改的值:

static final String TEST = "test variable";

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putInt(TEST, this.test);
    super.onSaveInstanceState(savedInstanceState);
}

Then in onCreate() method I put this code to get and show the changed "test" value: 然后在onCreate()方法中,我将此代码用于获取并显示已更改的“test”值:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState != null) {
        this.test = savedInstanceState.getInt(TEST);
        TextView textView1 = (TextView)findViewById(R.id.textView1);
        textView1.setText("Current test value is: " + test);
    }
}

So I open the application, press the button to change the "test" value from 1 to 2, then exit the application, wait until it's properly removed from memory (when Application Manager doesn't show it in "Cached processes" window), start the application again and textView1 view shows 1 instead of 2. What am I doing wrong? 所以我打开应用程序,按下按钮将“test”值从1更改为2,然后退出应用程序,等待它从内存中正确删除(当应用程序管理器未在“缓存进程”窗口中显示它时),再次启动应用程序,textView1视图显示1而不是2.我做错了什么? Please help! 请帮忙! Thanks! 谢谢!

正如Developer.android中记录的那样,Saved实例只保存你的Activity状态,它不会保存你想要的变量,我建议你改用SharedPreference

What am I doing wrong? 我究竟做错了什么?

Nothing. 没有。 Instance state does not cover the scenario that you are describing. 实例状态不包括您描述的方案。

Mostly, instance state is used in configuration changes (eg, screen rotation). 大多数情况下,实例状态用于配置更改(例如,屏幕旋转)。 Secondarily, instance state is used if the user leaves your app by means other than "exit" (by which I assume you mean BACK) and returns to you via means like the recent-tasks list. 其次,如果用户通过“退出”以外的方式离开您的应用程序(我假设您的意思是BACK),则使用实例状态,并通过最近任务列表等方式返回给您。

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

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