Android常用定时器的实现方式

手机APP/开发
285
0
0
2023-02-02
标签   Android
目录
  • 前言
  • 一、Handler 与 sleep
  • 二、Handler 与 postDelayed
  • 三、Handler 与 timer
  • 以下结论来源其他博主
  • 补充:采用Handler与timer及TimerTask结合的方法
  • 总结 

前言

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();
    }
}

结果打印如下:

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

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);
    }
}

结果打印如下:

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

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);
    }
}

结果打印如下:

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。

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);
    }
}
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);
    }
}
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);
    }
}

以下结论来源其他博主

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

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

在AlarmService中,拔掉USB线,按下电源键,过一点时间再次打开屏幕,发现定时器一直在计数。

测试机型小米8,上timer,下AlarmService

补充:采用Handler与timer及TimerTask结合的方法

1. 定义定时器、定时器任务及Handler句柄

private final Timer timer = new Timer();
private TimerTask task;
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        // 要做的事情
        super.handleMessage(msg);
    }
};

2. 初始化计时器任务

task = new TimerTask() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);
    }
};

3. 启动定时器

timer.schedule(task, 2000, 2000);