如果后台的Activity被系统回收了,如何在被回收之前保存当前状态。

调用 onSaveInstanceState() 方法保存数据:

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putString("state", textView.getText().toString());
    }

在 onCreate() 中恢复保存的数据:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(savedInstanceState != null){
            String text = savedInstanceState.getString("state");
        }
        textView = findViewById(R.id.textView);
    }

 

更多内容戳我&

你可能感兴趣的:(Android,理论知识)