Android開發 用Runnable做計時器遞增範例

Runnable物件用法

private Handler mIncHandler = new Handler();
`</pre>

<pre>`mIncHandler.postDelayed(mIncRunner, 1000);
`</pre>

<pre>`    private Runnable mIncRunner = new Runnable() {
        @Override
        public void run() {
            //執行內容
            mIncHandler.postDelayed(mIncRunner, 1000);
        }
    };
`</pre>

### 範例程式碼

<pre>`public class MainActivity extends AppCompatActivity {

    private Handler mIncHandler = new Handler();
    private boolean mCounterEnable = true;
    private int mCounter;

    //skip....
`</pre>

### 範例程式碼

<pre>`    @Override
    protected void onResume() {
        super.onResume();

        //讀取共用偏好設定中的計數值
        SharedPreferences sp = this.getPreferences( this.MODE_PRIVATE );
        mCounter = sp.getInt("to.fili.testinctimer.ooxxoioi", 0);

        //啟動計時器
        mCounterEnable = true;
        mIncHandler.postDelayed(mIncRunner, 1000);

        //偵錯用
        ((TextView)findViewById(R.id.nothing)).setText( String.valueOf(mCounter) );
    }
`</pre>

### 範例程式碼

<pre>`    @Override
    protected void onPause() {
        super.onPause();

        //指定計時器在下次執行後,暫停
        mCounterEnable = false;
    }
`</pre>

### 範例程式碼

<pre>`    private Runnable mIncRunner = new Runnable() {
        @Override
        public void run() {
            //累加計數值
            mCounter = mCounter+1;

            //將計數值存回共用偏好設定中
            SharedPreferences sp = MainActivity.this.getPreferences(MainActivity.this.MODE_PRIVATE );
            SharedPreferences.Editor spe = sp.edit();
            spe.putInt("to.fili.testinctimer.ooxxoioi", mCounter);
            spe.commit();

            //若計時器仍啟動中,設定下次執行(延遲)時間
            if(mCounterEnable) {
                mIncHandler.postDelayed(mIncRunner, 1000);
            }

            //偵錯用
            ((TextView)findViewById(R.id.nothing)).setText(String.valueOf(mCounter));
        }
    };