Android倒计时的几种方式
16lz
2021-01-26
方法一:使用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(); }
这个还不错
更多相关文章
- 地图测试
- Androidstudio实现手机摇一摇功能
- android handler和message的常用方法
- Android通过广播接收者调用服务内方法
- 文件File path与content:// Uri的相互转换
- android 一步一步创建jni示例
- Telephony单元测试分析
- Android(安卓)开启关闭软键盘
- Android数据库升级、降级、创建(onCreate() onUpgrade() onDowng