Android timer

In android development, the common timer implementation methods are as follows:

1. Handler and sleep

2、Handler与postDelayed

3、Trade and hours

Note: The main function of the Handler is to process the received information; the message passing mechanism of the Handler is used to ensure thread safety while multiple threads update the UI concurrently;

1. Handler and 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();
    }
}

The result is printed as follows:

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

Two, Handler and 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);
    }
}

The result is printed as follows:

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

3. Handler and 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);
    }
}

The result is printed as follows:

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

There are two commonly used timers on Android, one is Java.util.Timer, and the other is the system's 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);
    }
}

The following conclusions come from other bloggers (during the verification process, the boy connected to the usb normally, but after unplugging the usb, it does not match the conclusion, it may be that there is something wrong with the boy’s writing)

In Timer, when you connect the USB cable for debugging, you will find that everything is working normally, and the interface is updated every 5 seconds, even if you press the power button, it will still be triggered once every 5 seconds. After unplugging the USB cable, pressing the power button to turn off the screen, and turning it on again after a while, it was found that the timer obviously did not continue to count, and stayed at the number when the power button was turned off.
In AlarmService, unplug the USB cable, press the power button, turn on the screen again after a while, and find that the timer has been counting.

Test model Mi 8, on timer, off AlarmService
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/Twan1234/article/details/125050488