Android Timer (Handler timer Thread Alarmmanager countdowntimer)

Source: Internet
Author: User

The Android implementation of timed tasks generally uses the above (Handler Timer Thread Alarmmanager countdowntimer) Five ways. Of course there are many combinations (such as handler+thread, such as handler postdelyed such as Handler+timer+timertask) in a way not explained, It's not a problem to know that every small part of the use is used together.

In this paper, a simple implementation of 1s let the number plus 1 a small instance. (Consider a one-click scenario.) Consecutive clicks need to control the logic that does not end when the click is not allowed)

One: Use 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 (1,1000) when clicking on an event; Mhandler.removemessages (1) can be used; handler is canceled.

Two: Use a timer. Use TimerTask when using a timer. Also very simple 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, 1000);
}

Just call this method directly when you click on it. The previous 1000 indicates how long the execution begins. The following 1000 indicates how often to execute. Other overloaded functions with the same name. By looking at the method name, you know what each function does.

Three: Use thread, use this personal feeling and timer similar. is to open a thread + delay operation. So 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 timing time via 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;
}
}

Click Time to call Startthread () just fine.

Four: Use Alarmservice. In fact, through the alarmmanager to achieve. The most common place to use Alarmmanager in Android is the alarm clock. Look at this name to know is to start a system-level service to complete. Post code:

Private String Action_name = "Alarmservice";
private void Alarmservicestart () {
Register a 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);
5 seconds, one cycle, no stop sending broadcasts.
Am.setrepeating (alarmmanager.elapsed_realtime_wakeup
, firstime,1000, sender);
}
Register a 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 for Android package. Very convenient to use: the following

/**

* Using Countdowntimer is actually an Android packaged Countdown class
* Note that the 10*1000 here means that the total time is 10s 1000 indicates how often to execute
*/
Private Countdowntimer Countdowntimer = new Countdowntimer (10*1000, 1000) {
@Override
public void OnTick (long millisuntilfinished) {
Tvnum.settext ((Integer.parseint (Tvnum.gettext (). toString ()) +1) + "");
}
@Override
public void OnFinish () {
Tvnum.settext ("Execution End");
}
};

Summary: The usage is actually very simple. But it is because there are many ways to realize that you do not know which one to use. Personal advice:

1, the use of Countdown (time-limited hours of sale countdown, get Verification Code countdown) can be implemented using the fifth method. (Do not consider custom components)

2, the picture of the carousel, banner and the like can use handler and timer (thread almost). Implement timing slippage. (Do not consider custom components)

3. Use Alarmservice when using some of the more stringent requirements for specific times. Here's a description: The mechanism of the Android system lock, that is, when the system detects a period of inactivity, it shuts down unnecessary services to reduce resource and power consumption. Using a timer and service is likely to happen when the screen goes out and the service is stopped, and of course the polling is stopped. The current carousel stop has little effect on us. But a certain situation can cause a great loss. Like the alarm clock: Stop, can you still get up?

Here is also a fourth kind of am setrepeating method. The set type is alarmmanager.elapsed_realtime when you apply hibernation, you do not perform scheduled tasks. When the setting type is alarmmanager.elapsed_realtime_wakeup, it is always executed.

The above views are my personal views. If there is no place to forget the great God advice. Have you noticed the place also forget the great God advice

Attach the project's GitHub address Https://github.com/tozzais/AndroidTimingTest

Android Timer (Handler timer Thread Alarmmanager countdowntimer)

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.