Android Timer (Handler Timer Thread AlarmManager CountDownTimer) and alarm Timer
Android uses the preceding five methods to implement scheduled tasks: Handler Timer Thread AlarmManager CountDownTimer. Of course there are still many combinations (for example, Handler + Thread, for example, postDelyed that comes with the Handler class, for example, Handler + Timer + TimerTask, it is of course not a problem to understand how each part is used together.
This article uses a simple example of adding 1 to the number by 1 s. (Consider clicking only once. You need to control the logic of continuous clicking when it is not over)
I. Handler:
Private Handler mHandler = new Handler (){
@ Override
Public void handleMessage (Message msg ){
If (msg. what = 1 ){
Log. e (TAG, "mHandler" + Thread. currentThread (). getName ());
TvNum. setText (Integer. parseInt (tvNum. getText (). toString () + 1) + "");
MHandler. sendEmptyMessageDelayed (1,1000 );
}
}
};
Call mHandler. sendEmptyMessageDelayed () when clicking an event. You can use mHandler. removeMessages (1); cancel handler.
2. Use Timer. TimerTask is used when Timer is used. It is also very easy to use:
Private void timer (){
Timer = new Timer ();
Timer. schedule (new TimerTask (){
@ Override
Public void run (){
Log. e (TAG, "Timer:" + Thread. currentThread (). getName ());
RunOnUiThread (new Runnable (){
@ Override
Public void run (){
TvNum. setText (Integer. parseInt (tvNum. getText (). toString () + 1) + "");
}
});
}
}, 1000,100 0 );
}
You can call this method directly when you click it. The first 1000 indicates how long it will take to start execution. The following 1000 indicates how long the execution will take. Other overload functions with the same name. By looking at the method name, you will know the role of each function.
3. Using Thread is similar to using Timer. All open a thread + delay operation. Therefore, the UI must be updated in the main thread.
Private MyThread thread;
Private class MyThread extends Thread {
Public boolean stop;
Public void run (){
While (! Stop ){
// Set the scheduled time through the sleep thread
Try {
Thread. sleep (1000 );
Log. e (TAG, "Thread:" + Thread. currentThread (). getName ());
RunOnUiThread (new Runnable (){
@ Override
Public void run (){
TvNum. setText (Integer. parseInt (tvNum. getText (). toString () + 1) + "");
}
});
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
};
};
Private void startThread () {// start thread
If (thread = null ){
Thread = new MyThread ();
Thread. start ();
}
}
Private void stopThread () {// end thread
If (thread! = Null ){
Thread. stop = true;
Thread = null;
}
}
Just click the time to call startThread.
4. Use alarmService. Actually, it is implemented through AlarmManager. The most common use of AlarmManager in Android is the alarm clock. By looking at this name, we can see that a system-level service is started. Code:
Private String ACTION_NAME = "alarmService ";
Private void alarmServiceStart (){
// Register Broadcast
RegisterBoradcastReceiver ();
// Start AlarmManager
Intent intent = new Intent (ACTION_NAME );
PendingIntent sender = PendingIntent
. GetBroadcast (this, 0, intent, 0 );
Long firstime = SystemClock. elapsedRealtime ();
AlarmManager am = (AlarmManager) getSystemService (ALARM_SERVICE );
// Send broadcast continuously for a period of 5 seconds
Am. setRepeating (AlarmManager. ELAPSED_REALTIME_WAKEUP
, Firstime, 1000, sender );
}
// Register Broadcast
Public void registerBoradcastReceiver (){
IntentFilter myIntentFilter = new IntentFilter ();
MyIntentFilter. addAction (ACTION_NAME );
RegisterReceiver (mBroadcastReceiver, myIntentFilter );
}
Private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver (){
@ Override
Public void onReceive (Context context, Intent intent ){
String action = intent. getAction ();
If (action. equals (ACTION_NAME )){
TvNum. setText (Integer. parseInt (tvNum. getText (). toString () + 1) + "");
}
}
};
V. CountDownTimer: This is actually a countdown class encapsulated by android. Easy to use:
/**
* CountDownTimer is actually a countdown class encapsulated by android.
* 10*1000 indicates the total time, that is, 10 s 1000 indicates the execution time.
*/
Private CountDownTimer countDownTimer = new CountDownTimer (10*1000,100 0 ){
@ Override
Public void onTick (long millisUntilFinished ){
TvNum. setText (Integer. parseInt (tvNum. getText (). toString () + 1) + "");
}
@ Override
Public void onFinish (){
TvNum. setText ("execution ended ");
}
};
Conclusion: The usage is actually very simple. However, it is because there are many methods to implement and you do not know which one to use. Personal suggestion:
1. You can use the fifth method to implement countdown (time-limited sale countdown and Verification Code countdown. (Do not consider custom components)
2. Handler and Timer (Thread) can be used for image carousel and banner ). Implement timed sliding. (Do not consider custom components)
3. Use alarmService when the execution requirements for specific time are strict. Here, we will explain the locking mechanism of the Android system, that is, after the system detects that the system is not active for a period of time, it will close unnecessary services to reduce resource and power consumption. If Timer and Service are used for implementation, it is very likely that after the screen is turned off for a period of time, the Service will be stopped, and of course the polling will be stopped. The current stop of carousel has little impact on us. However, stopping a specific situation can cause great losses. For example, when the alarm is stopped, can you get up again?
Another point here is the setRepeating method of the fourth am. When the set type is AlarmManager. ELAPSED_REALTIME, the scheduled task is not executed when the application is sleeping. When the set type is AlarmManager. ELAPSED_REALTIME_WAKEUP, it will always be executed.
The above points are my personal opinions. If something is wrong, forget your advice. Have you noticed anything?
Add the github address https://github.com/tozzais/AndroidTimingTest for the project