Android定时器
今天就来细数一下Android是如何创建定时器的,一般有五种常用方法。 请看下文。
一、利用Timer + TimerTask
就像它的名字一样,一看就知道可以用来做定时器。直接看代码:
1Timer timer = new Timer(); 2timer.schedule(new TimerTask() { 3 @Override 4 public void run() { 5 //todo what you want 6 } 7}, 0, 1000);
二、利用Handler + Runnable
代码举例:
1private Handler handler = new Handler(); 2private Runnable runnable = new Runnable() { 3 @Override 4 public void run() { 5 //todo what you want 6 handler.postDelayed(runnable, 1000); 7 } 8};
这样定义好后,是不会直接运行,需要在合适的地方调用一次如下代码:
1handler.postDelayed(runnable, 1000);//触发定时器
三、利用Thread
代码举例:
1 private class MyThread extends Thread { 2 public boolean stop = false; 3 public void run() { 4 while (!stop) { 5 //todo what you want 6 try { 7 Thread.sleep(1000); 8 } catch (InterruptedException e) { 9 e.printStackTrace(); 10 } 11 } 12 }; 13};
定好自己的定时线程类,然后启动:
1MyThread thread = new MyThread(); 2thread.start();
四、利用AlarmManager
AlarmManager是系统级闹钟服务,可以直接使用。
1//获取闹钟服务 2AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 3//todo what you want in the onCreate() of ClockActivity 4Intent intent = new Intent(MainActivity.this, ClockActivity.class); 5PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0); 6/* 7 *参数1表示闹钟类型,本例表示在睡眠状态下会唤醒系统并执行提示功能,该状态下闹钟使用绝对时间; 8 *参数2表示定时器启动时间,本例是现在就开始; 9 *参数3表示定时器的触发间隔,本例是1秒钟; 10 *参数4表示定时器的行为,本例是启动系统服务在活动间跳转; 11 */ 12alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, pi);
五、利用CountDownTimer(倒计时器)
就像它的名字一样,是跟咱们一般的定时器反着的。看代码:
1 //参数1:计时总时间,参数2:每次扣除时间数 2CountDownTimer cdt = new CountDownTimer(10000, 1000){ 3 @Override 4 public void onTick(long millisUntilFinished) 5 { 6 //todo what you want 7 } 8 9 @Override 10 public void onFinish() { 11 12 } 13}; 14cdt.start(); 15
