android开发中,常用定时器实现方式有以下几种:
1、Handler与sleep
2、Handler与postDelayed
3、Handler与timer
注:Handler的主要作用就是用来处理接收到的信息;用Handler消息传递机制是为了多个线程并发更新UI的同时,保证线程安全;
一、Handler 与 sleep
publicclassHandlerAndSleep{// 1、定义一个Handler类,用于处理接受到的Message.Handler handler =newHandler(Looper.getMainLooper()){@OverridepublicvoidhandleMessage(@NonNullMessage msg){super.handleMessage(msg);// do something eg.Log.d("HandlerAndSleep","HandlerAndSleep");}};// 2、新建一个实现Runnable接口的线程类classMyThreadimplementsRunnable{@Overridepublicvoidrun(){while(true){try{Thread.sleep(10000);Message message =newMessage();
message.what =1;
handler.sendMessage(message);}catch(Exception e){
e.printStackTrace();}}}}publicHandlerAndSleep(){//3、在需要启动线程的地方加入下面语句,启动线程后,线程每10s发送一次消息newThread(newMyThread()).start();}}
结果打印如下:
2022-05-30 11:30:42.320 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:30:52.324 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:31:02.326 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:31:12.335 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:31:22.338 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:31:32.339 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
2022-05-30 11:31:42.347 17864-17864/com.yh.study D/HandlerAndSleep: HandlerAndSleep
二、Handler 与 postDelayed
publicclassHandleAndPostDelayed{Handler handler =newHandler(){@OverridepublicbooleansendMessageAtTime(@NonNullMessage msg,long uptimeMillis){Log.d("HandleAndPostDelayed","HandleAndPostDelayed");returnsuper.sendMessageAtTime(msg, uptimeMillis);}};Runnable runnable =newRunnable(){@Overridepublicvoidrun(){// do something
handler.postDelayed(this,2000);}};HandleAndPostDelayed(){// 开启定时器
handler.postDelayed(runnable,2000);// 停止定时器// handler.removeCallbacks(runnable);}}
结果打印如下:
2022-05-30 14:32:41.533 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
2022-05-30 14:32:43.534 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
2022-05-30 14:32:45.537 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
2022-05-30 14:32:47.539 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
2022-05-30 14:32:49.546 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
2022-05-30 14:32:51.550 24351-24351/com.yh.study D/HandleAndPostDelayed: HandleAndPostDelayed
三、Handler 与 timer
publicclassHandlerAndTimer{privatefinalTimer timer =newTimer();privateTimerTask task;Handler handler =newHandler(){@OverridepublicvoidhandleMessage(@NonNullMessage msg){// do somethingLog.d("HandlerAndTimer","HandlerAndTimer");super.handleMessage(msg);}};publicHandlerAndTimer(){
task =newTimerTask(){@Overridepublicvoidrun(){Message message =newMessage();
message.what =1;
handler.sendMessage(message);}};//启动定时器 参数对应为 TimerTask 延迟时间 间隔时间
timer.schedule(task,2000,2000);}}
结果打印如下:
2022-05-30 14:43:40.922 25052-25052/com.yh.study D/HandlerAndTimer: HandlerAndTimer
2022-05-30 14:43:42.924 25052-25052/com.yh.study D/HandlerAndTimer: HandlerAndTimer
2022-05-30 14:43:44.925 25052-25052/com.yh.study D/HandlerAndTimer: HandlerAndTimer
2022-05-30 14:43:46.926 25052-25052/com.yh.study D/HandlerAndTimer: HandlerAndTimer
2022-05-30 14:43:48.927 25052-25052/com.yh.study D/HandlerAndTimer: HandlerAndTimer
在Android上常用的定时器有两种,一种是Java.util.Timer,一种就是系统的AlarmService。
publicclassMainActivityextendsAppCompatActivity{Handler handler =newHandler(){@OverridepublicvoidhandleMessage(@NonNullMessage msg){
tCount++;
timerTV.setText(tCount+"");super.handleMessage(msg);}};Timer timer =newTimer();int tCount =0;int sCount =0;TextView timerTV;TextView serviceTV;String ALARM_RECEIVER_ACTION ="com.yh.study.AlarmReceiver";@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);
timerTV =findViewById(R.id.timer_tv);
serviceTV =findViewById(R.id.service_tv);
timer.schedule(newTimerTask(){@Overridepublicvoidrun(){
handler.sendEmptyMessage(0);}},2*1000,5*1000);AlarmReceiver alarmReceiver =newAlarmReceiver(newHandler(){@OverridepublicvoidhandleMessage(@NonNullMessage msg){
sCount++;
serviceTV.setText(sCount+"");super.handleMessage(msg);}});IntentFilter intentFilter =newIntentFilter();
intentFilter.addAction(ALARM_RECEIVER_ACTION);registerReceiver(alarmReceiver, intentFilter);Intent intent =newIntent(ALARM_RECEIVER_ACTION);PendingIntent pendingIntent =PendingIntent.getBroadcast(MainActivity.this,0, intent,0);//AlarmManager alarmManager =(AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime(),
pendingIntent);}}
publicclassAlarmReceiverextendsBroadcastReceiver{Handler handler;AlarmReceiver(Handler handler){this.handler = handler;}@OverridepublicvoidonReceive(Context context,Intent intent){Log.d("onReceive","onReceive");
handler.sendEmptyMessage(0);Intent serviceIntent =newIntent(context,MyService.class);
context.startService(serviceIntent);}}
publicclassMyServiceextendsIntentService{publicMyService(){super("MyService");}@OverrideprotectedvoidonHandleIntent(@NullableIntent intent){AlarmManager alarmManager =(AlarmManager)getSystemService(Context.ALARM_SERVICE);Intent alarmIntent =newIntent("com.yh.study.AlarmReceiver");PendingIntent pendingIntent =PendingIntent.getBroadcast(this,0, alarmIntent,0);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+5*1000,
pendingIntent);}}
以下结论来源其他博主(小子在验证过程中,连接usb情况正常,拔掉usb后与结论不符,可能是小子哪里写的有问题)
在Timer中,当连接USB线进行调试时,会发现一切工作正常,每5秒更新一次界面,即使是按下电源键,仍然会5秒触发一次。 当拔掉USB线,按下电源键关闭屏幕后,过一段时间再打开,发现定时器明显没有继续计数,停留在了关闭电源键时的数字。
在AlarmService中,拔掉USB线,按下电源键,过一点时间再次打开屏幕,发现定时器一直在计数。
测试机型小米8,上timer,下AlarmService
版权归原作者 八块的红双喜 所有, 如有侵权,请联系我们删除。