当前位置:   article > 正文

Android之定时器_android 定时器

android 定时器

android开发中,常用定时器实现方式有以下几种:

1、Handler与sleep

2、Handler与postDelayed

3、Handler与timer

注:Handler的主要作用就是用来处理接收到的信息;用Handler消息传递机制是为了多个线程并发更新UI的同时,保证线程安全;

一、Handler 与 sleep

public class HandlerAndSleep {

    // 1、定义一个Handler类,用于处理接受到的Message.
    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            // do something eg.
            Log.d("HandlerAndSleep", "HandlerAndSleep");
        }
    };

    // 2、新建一个实现Runnable接口的线程类
    class MyThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(10000);
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public HandlerAndSleep() {
        //3、在需要启动线程的地方加入下面语句,启动线程后,线程每10s发送一次消息
        new Thread(new MyThread()).start();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

结果打印如下:

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

二、Handler 与 postDelayed

public class HandleAndPostDelayed {

    Handler handler = new Handler(){
        @Override
        public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
            Log.d("HandleAndPostDelayed", "HandleAndPostDelayed");
            return super.sendMessageAtTime(msg, uptimeMillis);
        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // do something
            handler.postDelayed(this, 2000);
        }
    };

    HandleAndPostDelayed() {
    	// 开启定时器
        handler.postDelayed(runnable, 2000);
		// 停止定时器
//        handler.removeCallbacks(runnable);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

结果打印如下:

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

三、Handler 与 timer

public class HandlerAndTimer {

    private final Timer timer = new Timer();
    private TimerTask task;
    Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            // do something
            Log.d("HandlerAndTimer", "HandlerAndTimer");
            super.handleMessage(msg);
        }
    };

    public HandlerAndTimer() {
        task = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        };
        //启动定时器 参数对应为 TimerTask 延迟时间 间隔时间
        timer.schedule(task, 2000, 2000);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

结果打印如下:

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
  • 1
  • 2
  • 3
  • 4
  • 5

在Android上常用的定时器有两种,一种是Java.util.Timer,一种就是系统的AlarmService。

public class MainActivity extends AppCompatActivity {

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            tCount++;
            timerTV.setText(tCount+"");
            super.handleMessage(msg);
        }
    };

    Timer timer = new Timer();
    int tCount = 0;
    int sCount = 0;
    TextView timerTV;
    TextView serviceTV;

    String ALARM_RECEIVER_ACTION = "com.yh.study.AlarmReceiver";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timerTV = findViewById(R.id.timer_tv);
        serviceTV = findViewById(R.id.service_tv);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        }, 2*1000, 5*1000);

        AlarmReceiver alarmReceiver = new AlarmReceiver(new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                sCount++;
                serviceTV.setText(sCount+"");
                super.handleMessage(msg);
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ALARM_RECEIVER_ACTION);
        registerReceiver(alarmReceiver, intentFilter);

        Intent intent = new Intent(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);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
public class AlarmReceiver extends BroadcastReceiver {

    Handler handler;
    AlarmReceiver(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("onReceive", "onReceive");
        handler.sendEmptyMessage(0);
        Intent serviceIntent = new Intent(context, MyService.class);
        context.startService(serviceIntent);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
public class MyService extends IntentService {
    public MyService() {
        super("MyService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent alarmIntent = new Intent("com.yh.study.AlarmReceiver");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5*1000,
                pendingIntent);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

以下结论来源其他博主(小子在验证过程中,连接usb情况正常,拔掉usb后与结论不符,可能是小子哪里写的有问题)

在Timer中,当连接USB线进行调试时,会发现一切工作正常,每5秒更新一次界面,即使是按下电源键,仍然会5秒触发一次。 当拔掉USB线,按下电源键关闭屏幕后,过一段时间再打开,发现定时器明显没有继续计数,停留在了关闭电源键时的数字。
在AlarmService中,拔掉USB线,按下电源键,过一点时间再次打开屏幕,发现定时器一直在计数。

测试机型小米8,上timer,下AlarmService
在这里插入图片描述
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/240561
推荐阅读
相关标签
  

闽ICP备14008679号