方法一:使用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,"時間到",Toast.LENGTH_LONG).show();
Log.e(TAG, "testCountDown: end currentTimeMillis = "+System.currentTimeMillis() );
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if(countDownHandler != null)
{
//移除回調,避免內存泄漏
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,"時間到",Toast.LENGTH_LONG).show(); //time線程不能改變UI
// startActivity(MainActivity.class);//不能更新UI,但是可以啟動activity
}
};
Log.e(TAG, "testCountDown: start currentTimeMillis = "+System.currentTimeMillis() );
timer.schedule(timerTask,3000);
}
`雖然相差0毫秒,但是Timer并不能保證準時執行任務的,需要看前面的任務有沒有執行完。
方法三: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();
}
這個還不錯