当一个activity被回收之后,又返回这个activity时,会重新调用onCreate方法,此时,保存在activity的数据都会消失。我们重写onSaveInstanceState方法就可以保存临时数据了。
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
String tempData = "Something you just typed";
outState.putString("data_key", tempData);
}
//我们可以在onCreate方法中取得保存的全部数据
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null) {
String tempData = savedInstanceState.getString("data_key");
}
}
Activity的启动模式
//Activity有四种启动模式standard、singleTop、singleTask、singleInstance。
//可以在AndroidManifest.xml中给<activity>标签指定android:launchMode属性来选择启动模式
小知识
getTaskId() 可以返回当前栈的id
getClass().getSimpleName(); //获取当前实例的类名
管理所有的Activity
public class ActivityCollector {
public static List<Activity> activities = new ArrayList<Activity>();
public static void addActivity(Activity activity) {
activities.add(activity);
}
public static void removeActivity(Activity activity) {
activities.remove(activity);
}
public static void finishAll() {
for (Activity activity : activities) {
if(!activity.isFinishing()) {
activity.finish();
}
}
}
}
#通过继承,我们可以改写方法,使我们新建的类能管理
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
}
#我们经常要启动一个Activity,但是也许是别人写的,我们不知道要传什么参数,
#写一个函数actionStart看参数列表就知道传什么样的参数了
public static SecondActivity extends BaseActivity {
public static void actionStart(Context context, String data1,String data2) {
Intent intent = new Intent(context, Second.class);
intent.putExtra("param1", data1);
intent.putExtra("param2", data2);
context.startActivity(intent);
}
}
SecondActivity.actionStart(FirstActivity.this, "data1", "data2");
网友评论