Android倒計(jì)時(shí)的幾種方式

方法一:使用Handler+Runnable

public class CountDownActivity extends AppCompatActivity {

    private static final String TAG = "CountDownActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_count_down);

        testCountDown();
    }

    private void testCountDown() {

        Log.e(TAG, "testCountDown: start  currentTimeMillis = "+System.currentTimeMillis() );

        countDownHandler.postDelayed(countDownRunnable,3000);
    }

    Handler countDownHandler = new Handler();
    Runnable countDownRunnable = new Runnable() {
        @Override
        public void run() {

            Toast.makeText(context,"時(shí)間到",Toast.LENGTH_LONG).show();
            Log.e(TAG, "testCountDown: end  currentTimeMillis = "+System.currentTimeMillis() );
        }
    };


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

        if(countDownHandler != null)
        {
            //移除回調(diào),避免內(nèi)存泄漏
            countDownHandler.removeCallbacks(countDownRunnable);
        }
    }
}

相差10毫秒左右

方法二: Timer+TimerTask

    private void testCountDown() {


        final Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {

                Log.e(TAG, "testCountDown: end  currentTimeMillis = "+System.currentTimeMillis() );
                Log.e(TAG, "run: "+Thread.currentThread() );
                timer.cancel();
//                Toast.makeText(context,"時(shí)間到",Toast.LENGTH_LONG).show(); //time線程不能改變UI
//                startActivity(MainActivity.class);//不能更新UI,但是可以啟動(dòng)activity

            }
        };
        Log.e(TAG, "testCountDown: start  currentTimeMillis = "+System.currentTimeMillis() );
        timer.schedule(timerTask,3000);
    }

`雖然相差0毫秒,但是Timer并不能保證準(zhǔn)時(shí)執(zhí)行任務(wù)的,需要看前面的任務(wù)有沒(méi)有執(zhí)行完。

方法三:CountDownTimer

    private void testCountDown(){

        CountDownTimer countDownTimer = new CountDownTimer(3000,1000) {

            @Override
            public void onTick(long millisUntilFinished) {

                Log.e(TAG, "onTick: "+ millisUntilFinished);
            }

            @Override
            public void onFinish() {

                Log.e(TAG, "onFinish: " );
            }
        };

        countDownTimer.start();
//        countDownTimer.cancel();
    }


這個(gè)還不錯(cuò)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容