1, 存数据
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO 现场保护 -- 保存一些业务数据 onPause() 方法后调用
super.onSaveInstanceState(outState);
//存入数据
outState.putInt("index", index);
}
2, 获取数据
在onCreate()方法中
if(savedInstanceState!=null)
index = savedInstanceState.getInt("index");
当程序处于 onpause() onstop() onDestroy()时候,会被系统kill掉,之前的数据若是没有保存的话,那么就会丢失,我们希望可以保存之前的数据,可以在之前的数据基础是继续操作,那么保存数据 就是 我们所说的数据 保护,
在一个activity被杀死之前被调用,可以保存它的一些状态数据,存在一个bundle对象中,这个对象可以在下次启动程序调用onCreate(Bundle)或onRestoreInstanceState(Bundle)时作为传递的参数,这也就是为什么我们每一个activity重写的onCreate方法都有这么一段:
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}。
onSaveInstanceState(Bundle) 里面的这个Bundle对象和onCreate中的所指相同对象。
demo:
package com.example.weekday;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView tv1;
private Button btn1,btn2;
int index = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
tv1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv1.setTextColor(Color.rgb((int)Math.random()*256, (int)Math.random()*256, (int)Math.random()*256));
}
});
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, InfoActivity.class);
startActivity(intent);
}
});
if(savedInstanceState!=null){
//取出数据
index = savedInstanceState.getInt("index");
}
}
//保存值
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
//存入数据
outState.putInt("index", index);
}
public void addIndex(View view){
Toast.makeText(this, "当前进度 " + (index++), Toast.LENGTH_SHORT).show();
}
}