无法使用onSaveInstanceState保存布尔值

时间:2017-11-12 22:06:56

标签: android restore

我想使用onSaveInstanceState保存布尔变量,因此当我回到Activity时,该值将会更改。 由于某种原因,它不会发生。这是我的代码

public class MainActivity extends AppCompatActivity {
....
public boolean appLanched=true;

//switch to PassActivity
private void toPW() {
Intent intentToPW = new Intent(this, PassActivity.class);
startActivity(intentToPW);
}
    ....
//back in MainActivity
        @Override
     protected void onSaveInstanceState(Bundle outState) {
     super.onSaveInstanceState(outState);
     //variable to change state to "false"
     outState.putBoolean("appLanched", false);
    }
  @Override
     protected void onRestoreInstanceState(Bundle savedInstanceState) {
     super.onRestoreInstanceState(savedInstanceState);
     appLanched=savedInstanceState.getBoolean("appLanched");
                      }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//adding this   
 if (savedInstanceState!=null){
        appLanched=savedInstanceState.getBoolean("appLanched");
    } 
 //only if `true` switch Activity  
            if(appLanched) {
        toPW();
    }
    ...

运行并调试它我发现不是切换回MainActivity,而是立即返回到PassActivity,并且它不会执行onRestoreInstanceState方法。

0 个答案:

没有答案