Android several timer mechanisms and differences

Source: Internet
Author: User

In Android, frequently used timers are mainly implemented in the following ways:
The sleep (long) method using handler and thread
Second, using handler postdelayed (Runnable, Long) method
Third, the use of handler and timer and TimerTask combination method.
Here are the following:
The sleep (long) method using handle and thread
Handler is primarily used to handle received messages. This is only the main method, of course, there are other ways to achieve handler, interested in the API can be checked, there is not too much explanation.
1. Define a handler class to handle the received message.
Handler Handler = new Handler () {
public void Handlemessage (Message msg) {
The things to Do
Super.handlemessage (msg);
}
};
2. Create a new thread class that implements the Runnable interface. As follows:
public class MyThread implements runnable{
@Override
public void Run () {
TODO auto-generated Method Stub
while (true) {
try {
Thread.Sleep (10000);//thread paused for 10 seconds, per millisecond
Message message=new message ();
Message.what=1;
Handler.sendmessage (message);//Send Message
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
3. Add the following statement where you want to start the thread:
New Thread (New MyThread ()). Start ();
4. After the thread is started, the thread sends a message every 10s.
Second, using handler postdelayed (Runnable, Long) method
This implementation is relatively simple:
1. Handler handler=new Handler ();
Runnable runnable=new Runnable () {
@Override
public void Run () {
TODO auto-generated Method Stub
The things to Do
Handler.postdelayed (this, 2000);
}
};
2. Start the timer:
Handler.postdelayed (Runnable, 2000);//Perform runnable once every two seconds.
3. Stop the timer:
Handler.removecallbacks (runnable);
Third, the use of handler and timer and TimerTask combination method.
1. Define timer, timer task and handler handle
Private Final Timer timer = new timer ();
Private TimerTask task;
Handler Handler = new Handler () {
@Override
public void Handlemessage (Message msg) {
TODO auto-generated Method Stub
The things to Do
Super.handlemessage (msg);
}

};
2. Initialize the timer task.
task = new TimerTask () {
@Override
public void Run () {
TODO auto-generated Method Stub
Message message = new Message ();
Message.what = 1;
Handler.sendmessage (message);
}
};
3. Start the timer
Timer.schedule (Task, 2000, 2000);
Briefly describe some of the things mentioned in the three steps above.
1. Timer task (TimerTask) as the name implies, that is, when the timer arrives at the specified time to do the work, here is to handler send a message, by the handler class for processing.
2. Java.util.Timer.schedule (timertask task, long delay): This method means that the task is executed after dalay/1000 seconds. Only once.
Java.util.Timer.schedule (timertask task, long delay, long period): This method is to say that the task is executed after delay/1000 seconds and then into period/ 1000 seconds to execute the task again, this is used for looping tasks, executed countless times, of course, you can use Timer.cancel (); Cancel the execution of the timer.

//////////////////////////////////////////////////////

And then it's about Java.util.Timer and Alarmservice.

There are two kinds of timers commonly used on Android, one is Java.util.Timer, the other is the alarmservice of the system.


Experiment 1: Use Java.util.Timer.
Create a timer at OnStart (), update the counter every 5 seconds, and start.
Java code
Mtimer = new Timer ();
Mtimer.schedule (New TimerTask () {
@Override
public void Run () {
++mcount;
Mhandler.sendemptymessage (0);

}
}, 5*1000, 5*1000);

Mtimer = new Timer ();
Mtimer.schedule (New TimerTask () {
@Override
public void Run () {
++mcount;
Mhandler.sendemptymessage (0);
}
}, 5*1000, 5*1000);

When connected to the USB cable for debugging, it will find that everything is working properly, update the interface every 5 seconds, even if the power button is pressed, will still be triggered 5 seconds.
When the USB cable is unplugged, press the Power key to turn off the screen, after a period of time to open again, found that the timer obviously did not continue to count, stuck in the power button off the number.

Lab 2: Using Alarmservice:
2.1 A broadcast is sent by Alarmservice each 5 seconds, and the setrepeating type is alarmmanager.elapsed_realtime.
Java code
Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);
Am.setrepeating (Alarmmanager.elapsed_realtime, Firsttime, 5*1000, sender);

Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);
Am.setrepeating (Alarmmanager.elapsed_realtime, Firsttime, 5*1000, sender);

Unplug the USB cable, press the power button, open the screen again after a while, and notice that the timer does not continue to count.
2.2setRepeating Yes type set to Alarmmanager.elapsed_realtime_wakeup
Java code
Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);
Am.setrepeating (Alarmmanager.elapsed_realtime_wakeup, Firsttime, 5*1000, sender);

Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);
Am.setrepeating (Alarmmanager.elapsed_realtime_wakeup, Firsttime, 5*1000, sender);

Unplug the USB cable, press the power button, turn on the screen a little longer, and find that the timer is counting.

In this case, the use of wakeup to ensure that the timer you want to work, but it will certainly cause increased power consumption.

///////////////////////////////////////

The last is the difference between schedule and scheduleatfixedrate

Schedule and Scheduleatfixedrate differences:

(1) Schedule of 2 parameters when scheduling a task, the task is executed immediately if the specified schedule execution time scheduledexecutiontime<= systemcurrenttime. Scheduledexecutiontime does not change because of the excessive execution of a task.
(2) Schedule of 3 parameters when formulating a plan to execute a task repeatedly, the scheduled execution time for each execution of the task changes with the actual execution time of the previous one, that is, scheduledexecutiontime (n+1) = Realexecutiontime (nth time) +periodtime. That is, if the nth execution of a task, for some reason the execution time is too long, after the execution of the systemcurrenttime>= scheduledexecutiontime (n+1), then do not wait for a moment, immediately execute the first n+ 1 tasks, and the next n+2 task Scheduledexecutiontime (n+2) becomes realexecutiontime (n+1 times) +periodtime. Plainly, this approach is more focused on keeping the interval stable.
(3) The scheduleatfixedrate of 3 parameters when formulating a plan to execute a task repeatedly, the scheduled execution time for each execution of the task is initially determined, i.e. scheduledexecutiontime (nth time) = Firstexecutetime +n*periodtime; If the nth execution of a task is for some reason the execution time is too long, after the execution of the systemcurrenttime>= scheduledexecutiontime (nth + 1 times), then do not do period interval wait, immediately execute the N+1 task, and the next n+2 task of Scheduledexecutiontime (n+2) still firstexecutetime+ (n+2) * Periodtime This is the first time that a task is executed. Plainly, this approach is more focused on maintaining the stability of the execution frequency.

Example of a timer:

Package Com.hemes.timer;

Import java.util.*;

public class Dotask extends TimerTask {

True when a background process thread is used. As long as the remaining program narrative runs, the background process thread executes.
Timer MyTimer;

public void Start (int delay, int hour) {
MyTimer = new Timer ();
Mytimer.schedule (this, delay *, hour*1000*60*60); Using the Timer.schedule method

public void Schedule (TimerTask task,long Time,long period)
The task is scheduled to execute after the delay time and executes every period (milliseconds) after execution. Since the specified time interval is not guaranteed to be exact with the clock, the party
}

public void Start (Date time, int hour) {
MyTimer = new Timer ();
Mytimer.schedule (this, time, hour*1000*60*60); Using the Timer.schedule method

public void Schedule (TimerTask task,date Time,long period)
The task is scheduled to execute at the time specified, and is executed every period (milliseconds) after execution. Since the specified time interval is not guaranteed to be exact with the clock, the party
}

public void Run () {
Perform task (SQL)
System.out.println ("Do Task ...");
}

public void End () {
Mytimer.cancel ();
Terminates the function execution of the timer, but does not have an impact on the task being performed. When the Cancel method is executed, it will no longer be used to assign tasks.
}

Test
public static void Main (String args[]) {

Dotask myTask1 = new Dotask ();

Get the Date corresponding to 11:30:00 pm today.
Calendar calendar = Calendar.getinstance ();
Calendar.set (Calendar.hour_of_day, 23);
Calendar.set (Calendar.minute, 30);
Calendar.set (Calendar.second, 0);
Date time = Calendar.gettime ();

Mytask1.start (time,24);



Mytask1.end ();//Thread End

}
}

Android several timer mechanisms and differences

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.