问题总结:

1、Activity完整的生命周期

2、当打开第二个Activity并关闭时候的生命周期。

①、解释为什么onPause()方法不要有耗时操作

3、Activity发生异常重启的时候
问题:1、异常的原因

4、Activity异常的生命周期

1、如何保存数据和获取数据 2、发现一些控件会自动保存数据 原理是什么

5、Activity异常的解决办法

①、防止屏幕旋转,并重启Activity

②、当键盘改变的时候,改变布局。

回答:

1、当发生异常重启的时候,如何保存数据和获取数据

步骤:1、重写onSaveInstance()方法   2、重写onRestoreInstance()或者在onCreate()方法获取存储的数据。

详细步骤:

1、创建MainActivity

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); }
}

MainActivity

2、重写onSaveInstance();

public class MainActivity extends AppCompatActivity {
//保存的数据
private String data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = "重启保存";
} @Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//将保存的数据存入Bundle中
outState.putString("data",data);
}
}

MainActivity

3、通过onCreate()获取数据

 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = "重启保存";
//当被重启的时候,savedInstanceState不为null且为onSaveInstanceState()中我们存储的数据
if (savedInstanceState != null){
data = savedInstanceState.getString("data");
}
}

MainActivity

4、通过onRestoreInstance()获取数据

    @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
data = savedInstanceState.getString("data");
}

MainActivity

完整代码:

public class MainActivity extends AppCompatActivity {
//保存的数据
private String data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = "重启保存";
//当被重启的时候,savedInstanceState不为null且为onSaveInstanceState()中我们存储的数据
if (savedInstanceState != null){
data = savedInstanceState.getString("data");
}
} @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
data = savedInstanceState.getString("data");
} @Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//将保存的数据存入Bundle中
outState.putString("data",data);
}
}

MainActivity

05-08 08:02