close

在旋轉螢幕或是系統主動回收activity時

就會需要recreate該activity

並且以key-value的形式來達成

 

1. 官網http://developer.android.com/training/basics/activity-lifecycle/recreating.html

流程為

a. activity被系統回收時會執行onSaveInstanceState()的method

b. 重新創造activity, 會從頭執行onCreate

c, 執行onRestoreInstanceState()的method把參數取回

01.png

 

2. 以下介紹一個簡單例子

keep是要被還原的變數

其中還原點可以設定在onCreate裡面並且判斷

    private int keep;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("TAG", "onCreate");
        if(savedInstanceState != null){
            keep = savedInstanceState.getInt("RESTORE_DATA");
            Log.d("TAG", "keep = " + keep);
        }else{
            keep = 0;
            Log.d("TAG", "keep = " + keep);
        }
    }

02.png

 

3. 然後在onSaveInstanceState將變數存放進去

onRestoreInstanceState的地方將變數復原

這個也可以在上一步的onCreate中實行

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d("TAG", "onSaveInstanceState");
        outState.putInt("RESTORE_DATA", 5);
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.d("TAG", "onRestoreInstanceState");
        keep = savedInstanceState.getInt("RESTORE_DATA");
        Log.d("TAG", "keep = " + keep);
    }

03.png

 

4. 最後可以看到log

上方的框是第一次創造activity時的情形

下方的框是轉屏後依序執行的狀況

04.png  

arrow
arrow
    文章標籤
    Android recreating activity
    全站熱搜
    創作者介紹
    創作者 RX1226 的頭像
    RX1226

    給你魚竿

    RX1226 發表在 痞客邦 留言(0) 人氣()