1. Timer
Timer is a class that directly starts a timer on Android. TimerTask is a child thread that is convenient for handling some more complex and time-consuming functional logic and is often used in combination with handlers.
Compared with the timer implemented by the handler itself, Timer can do some complex processing. For example, it is necessary to sort lists with a large number of objects. Execution in TimerTask will not block child threads. It is often used in combination with handler. After processing complex and time-consuming operations, the UI interface is updated through handler.
(task, delay,period);
task: A TimerTask type object. The run() method of implementing TimerTask is a task that needs to be executed periodically;
delay: The delay time from the timer initialization is successful.
period: The interval time of the timer.
The third parameter is the execution cycle, which is of long type.
TimerTask task= new TimerTask() { @Override public void run() { count++; ("MainActivity",count + ""); } }; new Timer().shedule(task,0,1000);//
Here are several methods for scheduling tasks:
//time is Date type: execute at a specified time
(task, time);
//firstTime is Date type, period is long, which means that it will be executed every milliseconds from the firstTime moment.
(task, firstTime,period);
//delay is a long type: delay is executed once every milliseconds from now on.
(task, delay);
//delay is long, period is long: After delay milliseconds are passed from now, execute every milliseconds.
(task, delay,period);
//time is Date type: executed once at the specified time.
(task, time);
//firstTime is Date type, period is long, which means that it will be executed every milliseconds from the firstTime moment.
(task, firstTime,period);
//delay is a long type: delay is executed once every milliseconds from now on.
(task, delay);
//delay is long, period is long: After delay milliseconds are passed from now, execute every milliseconds.
(task, delay,period);
Note: Cancel in (), otherwise a crash may occur
2. APP that uses TimerTask to perform certain operations regularly will still run in TimerTask for a while, but it cannot run for a long time.
3. For some mobile phones, if you directly update the UI thread in TimerTask, you will not report an error, and it runs normally, but be sure to update the UI must be executed in the main thread, otherwise you will understand when troubleshooting errors. Moreover, this thing consumes power, especially power, especially power consumption. I will say important things three times and must be turned off when not in use.
2. CountDownTimer
CountDownTimer cdt = new CountDownTimer(10000, 100) { @Override public void onTick(long millisUntilFinished) { tv_hello.setText(millisUntilFinished + ""); } @Override public void onFinish() { } }; ();
Methods in onTick once
Until 10000/100 times are executed, onFinish() will be executed at the end
3. AlarmManager
Intent intent2 = newIntent(,); PendingIntent pd=(getApplicationContext(),0,intent2,PendingIntent.FLAG_ONE_SHOT); AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); long triggerTime =() + 5*1000; (AlarmManager.ELAPSED_REALTIME,triggerTime, pd);
The above is the basic usage of the timer. First get the manager, then define the flag of the alarm clock, the loop time, and the pendingIntent issued by the specified time.
Generally, the pendingIntents sent are broadcasts. We can customize a broadcast receiver and receive this broadcast to process our own functional logic.
Here you need to pay attention to the configuration in an independent process, which is defined by Android.
<receiver android:name="" android:process=":remote" />
1. Alarm timing does not require the program to maintain itself, but the system is maintained, so that the program can better avoid error-prone problems, and occupy system resources and CPU share.
2. Even after the program exits, the program itself will not have any troubles. The system will automatically call the corresponding component to execute the defined logic at the time.
3. Diversity of timing, including one timing, loop timing (execution on x-month x year, xx year, Monday to Friday, and at what time every day...)
4. Handler
Handler can help us operate UI threads in child threads, such as child thread parsing data, and notify the UI to refresh the interface after parsing. It can also implement a timer.
private Handler handler = Handler() { public handleMessage( msg) { switch () { : // Remove all messages such as 0 to ensure that there is only one circular message queue before running (); // Functional logic processing of app ... // Issue msg again and update loop (, ); break; : // Remove directly, the timer stops (); break; default: break; } }; };
As long as the timer is started, (0), the timer will start. The method to continue looping and stopping has been written on the comments.
Each loop is operated in the main thread, avoiding interspersed interaction between the child thread and the main thread. I personally think it is easier to control than timer and the function implementation is also very simple.
I personally think it is more suitable for continuous update of the UI without complicated and time-consuming processing. For example, in the player, we need to update the display of the current playback progress. Just update the text display, using handler is a good choice.
5. Thread
Thread implementation timer is to create a child thread, which loops while in it, and you can update the UI through handler. I personally think there is no difference between Thread and Timer, but it looks different.
private MyThread thread; private class MyThread extends Thread { public boolean stop; public () { while (!stop) { // Processing function // Set the timing time through the sleep thread { (); } catch (InterruptedException e) { // TODO Auto-generated catch block (); } } }; }; /** * Start the thread * */ private start() { (thread == ) { thread = MyThread(); (); } } /** * Stop thread * */ private () { (thread != ) { = ; thread = ; } }
I think it's similar to Timer, but it has no special advantages
Similar to Timer, if multiple threads are not considered well, problems will often occur. Multiple threads with the same function often exist at the same time. Android itself has a limit on the number of use of child threads, and it is a terrible thing for an app to run multiple threads at the same time. Therefore, like Timer, you must consider it carefully when using it.
The above is a detailed explanation of the five examples of Android implementation timer introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!