Android程序优化之异常终止数据恢复

  • 当Activity异常终止时,系统会默认为我们保存部分数据 ,如果想自定义保存的数据以供恢复,可以重写onSaveInstanceState()来保存数据以及onRestoreInstanceState()来恢复数据。
  • onSaveInstanceState()是使用Bundle来保存数据,可写 如下测试代码:
   @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("mySave","保存的数据");
        Log.d("=======","onSaveInstanceState");
        super.onSaveInstanceState(outState);
    }
  • onRestoreInstanceState()和onCreate()都可以用来恢复数据,在onCreate里需要判断Bundle里面是否有值,而onRestoreInstanceState()的Bundle里面一定是有值的。而且经过测试,onCreate()比onRestoreInstanceState()先执行。
 @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        String save=savedInstanceState.getString("mySave");
        Log.d("=======","onRestoreInstanceState"+save);
        super.onRestoreInstanceState(savedInstanceState);
    }
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_text);
        if(savedInstanceState!=null){
            String save=savedInstanceState.getString("mySave");
            Log.d("=======","onCreate:"+save);
        }      
    }

运行结果如下:

=======: onSaveInstanceState =======: onCreate:保存的数据 =======: onRestoreInstanceState保存的数据

你可能感兴趣的:(android,优化,异常,保存数据)