android onSaveInstanceState的使用方法 – Android移動開發技術文章_手機開發 Android移動開發教學課程

 

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;

 }

}

You May Also Like