1. 程式人生 > >android Timer TimerTask 啟動與停止及常見無法停止問題解決

android Timer TimerTask 啟動與停止及常見無法停止問題解決

在程式設計中經常會用到定時器Timer

private void setTime(){
        time_right.setVisibility(View.VISIBLE);
        timer = new Timer(true);
        timerTask = new MyTimerTask();
        musicCurrentDuration = 0;
        timer.schedule(timerTask,0,1000);
    }
    private long musicCurrentDuration = 0;
    private MyTimerTask timerTask;
    private
class MyTimerTask extends TimerTask{ @Override public void run() { // int duration = mVideoView.getDuration(); musicCurrentDuration += 1000; if (musicCurrentDuration >= musicDuration){ cancel(); if (timer!= null){ timer.purge(); timer.cancel(); timer = null
; } runOnUiThread(new Runnable() { @Override public void run() { camera_start_pause.performClick(); } }); return; } // int currentPosition = mVideoView.getCurrentPosition();
try { final String s = TimeUtils.longToString(musicCurrentDuration, "mm:ss"); final String ss = TimeUtils.longToString(musicDuration,"mm:ss"); runOnUiThread(new Runnable() { @Override public void run() { time_right.setText(s+"/"+ss); } }); } catch (ParseException e) { e.printStackTrace(); } } };

這是一個使用場景,我們開啟定時器,執行timertask,注意,這個timertask每次都要重新new一個,否則會報錯。timer不需要。當定時器的timertask執行後,我們分兩種情況,一個是run方法內部的判斷生效,這時我們執行自己需要的操作,並且注意關閉timertask 和timer,而且注意順序先關閉timertask 再關閉timer,

如果我們提前手動處理了,計時器中的操作還未到時間,也需要關閉計時器,和上面一樣順序。
最好在onDestroy中也執行關閉操作

@Override
    protected void onDestroy() {
        super.onDestroy();

        if (timerTask != null){
            timerTask.cancel();
            timerTask = null;
        }
        if (timer != null){
            timer.cancel();
            timer.purge();
            timer = null;
        }

    }

還有一種timertask的寫法

 private void setTime(){
        if (timer==null) {
            time.setVisibility(View.VISIBLE);
            timer = new Timer(true);
            timer.schedule(timerTask, 0, 500);
        }
    }

    private TimerTask timerTask=new TimerTask() {
        @Override
        public void run() {
            if (mVideoView == null){
                return;
            }
            int duration = mVideoView.getDuration();
            int currentPosition = mVideoView.getCurrentPosition();
            try {
                final String s = TimeUtils.longToString(duration, "mm:ss");
                final String ss = TimeUtils.longToString(currentPosition,"mm:ss");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        time.setText(ss+"/"+s);
                    }
                });
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    };

這種方式只在timertask用一次,不會重複使用的情況下可以。否則報錯。關閉計時器方式和上方一樣,可在你想關閉的地方關閉。