android onSaveInstanceState的使用方法

 
 
package com.saveInstanceDemo.src;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class saveInstanceDemo extends Activity {
  
  
    private static final String TAG = "MyNewLog";
    private int mCount = 0;
    private boolean mThreadDisble;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // If an instance of this activity had previously stopped, we can
        // get the original text it started with.
        if(null != savedInstanceState)
        {
            int IntTest = savedInstanceState.getInt("IntTest");
            String StrTest = savedInstanceState.getString("StrTest");
            Log.e(TAG, "onCreate get the savedInstanceState+IntTest="+IntTest+"+StrTest="+StrTest);       
        }
        setContentView(R.layout.main);
      
        new Thread(new Runnable()
  {
   @Override
   public void run() {
    // TODO Auto-generated method stub
   
    while(true)
    {
     if(!mThreadDisble)
     {
      Log.v(TAG, Boolean.toString(mThreadDisble));
      try{
       Thread.sleep(1000);
      }
      catch(Exception e)
      {
       e.printStackTrace();
      }
      mCount++;
      Log.v(TAG, "mCount : " + mCount);
     }
    }    
   }
  }).start();
 
        Log.e(TAG, "onCreate");
    }
    @Override
    //为了防止万一程序被销毁的风险,这个方法可以保证重要数据的正确性
    //不写这个方法并不意味着一定出错,但是一旦遇到了一些非常奇怪的数据问题的时候
    //可以看看是不是由于某些重要的数据没有保存,在程序被销毁时被重置
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save away the original text, so we still have it if the activity
        // needs to be killed while paused.
      savedInstanceState.putInt("IntTest", mCount);
      savedInstanceState.putString("StrTest", "savedInstanceState test");
      super.onSaveInstanceState(savedInstanceState);
      Log.e(TAG, "onSaveInstanceState");
    }  
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onRestoreInstanceState(savedInstanceState);
      int mCount = savedInstanceState.getInt("IntTest");
      String StrTest = savedInstanceState.getString("StrTest");
      Log.e(TAG, "onRestoreInstanceState+IntTest="+mCount+"+StrTest="+StrTest);
    }
  
 public void onDestroy()
 {
  super.onDestroy();
  this.mThreadDisble = true;
 }
 
 public void onPause()
 {
  Log.v(TAG, "onPause");
  super.onPause();
  mThreadDisble = true;
 }
 
 public void onResume()
 {
  Log.v(TAG, "onResume");
  super.onResume();
  mThreadDisble = false;
 }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值