<span id="Label3"></p><p><p>Timing tasks in Android typically have two implementations, one using the Timer class provided in the Java API, and the Alarm mechanism for using ANDROID. Both of these approaches achieve similar results in most cases, but the timer has an obvious short board that is not quite suitable for timed tasks that need to run in the background for a long time. As we all know, in order to make the battery more durable, each phone will have its own hibernation strategy, the Android phone will be in a long time without the operation of the CPU automatically put into sleep, which may cause the timer task is not working properly. This is not the case with the Alarm mechanism, which has the ability to wake up the cpu, which guarantees that the CPU will function every time a scheduled task is Required. It's important to note that waking up the CPU and waking up the screen is not the same concept at all, so don't confuse it.</p></p><p><p>So first of all we look at the use of Alarm mechanism, it is not complicated, mainly by virtue of the Alarmmanager class to Achieve. This class and notificationmanager a bit similar, all by calling the Context of the Getsystemservice () method to get the instance, but here the parameters that need to be passed in is Context.alarm_service. thus, obtaining an instance of Alarmmanager can be written as:</p></p><p><p><strong>A</strong> <strong>La</strong> <strong>R</strong> <strong>MM</strong> <strong>a</strong> <strong>na</strong> <strong>g</strong> <strong>e</strong> <strong>R manager = (alarmmanager) Getsystemservice (context.alarm_service);</strong></p></p><p><p>Next Call the Alarmmanager set () method to set a timed task, for example, to set a task to execute after 10 seconds, it can be written as:</p></p><p><p><strong>long triggerattime = Systemclock.elapsedrealtime () + ten * Manager.set (alarmmanager.elapsed_realtime_wakeup, triggerattime, pendingintent); </strong>the above two lines of code you may not be able to see clearly, because the set () method needs to pass in the three parameters a little bit more complex, let's take a closer look at the Analysis. The first parameter is an integer parameter that specifies the type of work for the alarmmanager, with four values selectable, elapsed_realtime, elapsed_realtime_wakeup, RTC, and rtc_wakeup, respectively. Where elapsed_realtime indicates that the trigger time for a scheduled task is counted from the start of the system, but does not wake the CPU. The elapsed_realtime_wakeup also means that the trigger time of the scheduled task is counted from the start of the system, but it wakes up the CPU. The RTC indicates that the trigger time for a scheduled task starts from 0 o'clock on January 1, 1970, but does not wake the CPU. Rtc_wakeup also means that the trigger time for a scheduled task</p></p><p><p>January 1, 1970 0 O'Clock starts, But the CPU is Awakened. Use the Systemclock.elapsedrealtime () method to obtain the number of milliseconds that the system has elapsed since the time it was powered on, and use the System.currenttimemillis () method to obtain the millisecond of the time elapsed since 0 o'clock January 1, 1970. Number.</p></p><p><p>Then take a look at the second parameter, This parameter is good to understand more, that is, the timing of the task trigger time, in MILLISECONDS. If the first parameter uses Elapsed_realtime or elapsed_realtime_wakeup, then the time it takes to start the power up here plus the time to delay Execution. If the first parameter uses RTC or rtc_wakeup, this is the time of January 1, 1970, 0 o'clock, plus the time of the deferred Execution. The third parameter is a pendingintent, you should be no stranger to it. Here we will generally adjust</p></p><p><p>Use the Getbroadcast () method to obtain a pendingintent that can perform the Broadcast. This allows the OnReceive () method of the broadcast receiver to be executed when the timed task is Triggered.</p></p><p><p>Once you understand each parameter of the set () method, you should be able to imagine that setting a task to execute after 10 seconds can also be written as:</p></p><p><p></p></p><p><p><strong>long triggerattime = System.currenttimemillis () + ten *, manager.set (alarmmanager.rtc_wakeup, triggerattime, pendingintent); </strong>well, Now that you have mastered the basic usage of the Alarm mechanism, Let's create a service that can perform timed tasks in the background for a long time. Create a Servicebestpractice project, and then add a Longrunningservice</p></p><p><p>class, The code looks like This:</p></p><p><p></p></p><p><p><strong>public class Longrunningservice extends Service {</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>Public IBinder Onbind (Intent Intent) {</strong></p></p><p><p><strong>Return null;</strong></p></p><p><p><strong>}</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>public int Onstartcommand (Intent Intent, int flags, int Startid) {</strong></p></p><p align="center"><p align="center"><strong>New Thread (new Runnable () {</strong></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>public void Run () {</strong></p></p><p><p><strong>LOG.D ("longrunningservice", "executed at" + new Date ().</strong></p></p><p><p><strong>ToString ());</strong></p></p><p><p><strong>}</strong></p></p><p><p><strong>}). Start ();</strong></p></p><p><p><strong>Alarmmanager manager = (alarmmanager) Getsystemservice (alarm_service);</strong></p></p><p><p><strong>int anhour = 60 * 60 * 1000; </strong>This is the number of milliseconds in an Hour.</p></p><p><p><strong>Long Triggerattime = Systemclock.elapsedrealtime () + anhour; Intent i = new Intent (this, alarmreceiver.class); pendingintent pi = pendingintent.getbroadcast (this, 0, i, 0);</strong></p></p><p><p><strong>Manager.set (alarmmanager.elapsed_realtime_wakeup, triggerattime, pi);</strong></p></p><p><p><strong>return Super.onstartcommand (intent, flags, startid);</strong></p></p><p><p><strong>}</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>}</strong></p></p><p><p>We open a sub-thread in the Onstartcommand () method, and then we can perform a specific logical operation in the thread of the child Line. For the sake of simplicity, just print out the current Time.</p></p><p><p>The code behind the creation of the thread is the use of the Alarm mechanism we just explained, first obtaining an instance of alarmmanager, then defining the Task's trigger time of one hour, and then using Pendingintent to specify the broadcast receiver that handles the scheduled task as alarmreceiver, and finally calls the set () method to complete the Setting.</p></p><p><p>obviously, Alarmreceiver does not exist yet, so the next step is to create a new Alarmreceiver class and let it inherit from broadcastreceiver, as shown in the following code:</p></p><p><p></p></p><p><p><strong>public class Alarmreceiver extends Broadcastreceiver {</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>public void OnReceive (context context, Intent Intent) {</strong></p></p><p><p><strong>Intent i = new Intent (context, longrunningservice.class);</strong></p></p><p><p><strong>Context.startservice (i);</strong></p></p><p><p><strong>}</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>}</strong></p></p><p><p>The code in the OnReceive () method is very simple, which is to build a Intent object and then start the Longrunningservice service. So why do you write this here? In fact, unconsciously, This has been a long time in the background to run the service Completed. Because once the Longrunningservice is started, a timed task is set in the Onstartcommand () method, so that the Alarmreceiver onreceive () method will be executed an hour later, and then we'll start again here longrunningservice, so that the formation of a permanent cycle, to ensure that the longrunningservice can be started every hour, a long time in the background of the service run in a timely way to complete the Natural.</p></p><p><p>The next task is also very clear, that is, we need to open the program when the longrunningservice, and then Longrunningservice can be run all the Time. Modify the code in the mainactivity as Follows:</p></p><p><p></p></p><p><p><strong>public class Mainactivity extends Activity {</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>@Override</strong></p></p><p><p><strong>protected void OnCreate (Bundle Savedinstancestate) {</strong></p></p><p><p><strong>Super.oncreate (savedinstancestate);</strong></p></p><p><p><strong>Intent Intent = new Intent (this, longrunningservice.class);</strong></p></p><p><p><strong>StartService (intent);</strong></p></p><p><p><strong>}</strong></p></p><p><p></p></p><p><p></p></p><p><p><strong>}</strong></p></p><p><p>finally, Let's not forget that the services and broadcast receivers we use are registered in androidmanifest.xml, and the code looks like This:</p></p><p><p></p></p><p><p><strong><manifest xmlns:android= "http://schemas.android.com/apk/res/android"</strong> <strong>package= "com.example.servicebestpractice"</strong></p></p><p><p><strong>android:versioncode= "1" android:versionname= "1.0" ></strong></p></p><p><p>......</p></p><p><p><strong><application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@style/apptheme" ></strong></p></p><p><p><strong><activity android:name= "com.example.servicebestpractice.MainActivity" android:label= "@string/app_name" ></strong></p></p><p><p><strong><intent-filter></strong></p></p><p><p><strong><action android:name= "android.intent.action.MAIN"/></strong></p></p><p><p><strong><category android:name= "android.intent.category.LAUNCHER"/></strong></p></p><p><p><strong></intent-filter></strong></p></p><p><p><strong></activity></strong></p></p><p><p><strong><service android:name= ". Longrunningservice "></strong></p></p><p><p><strong></service></strong></p></p><p><p><strong><receiver android:name= ". Alarmreceiver "></strong></p></p><p><p><strong></receiver></strong></p></p><p><p><strong></application></strong></p></p><p align="center"><p align="center"><strong></manifest></strong></p></p><p><p>Now you can run the Program. Although you will not see any useful information on the interface, the Longrunningservice is actually running quietly in the Background. In order to be able to verify the results of the operation, I left my phone idle for a few hours and then observed the print log in LogCat, as shown in 9.15.</p></p><p><p></p></p><p align="center"><p align="center">Figure 9.15</p></p><p><p>As you can see, Longrunningservice is running as we wish, printing a log every Hour. This way, when you really need to perform a timed task, just replace the print log with the specific task Logic.</p></p><p><p>It is also important to note that, starting with Android 4.4, the trigger time of the Alarm task will become inaccurate and it may be delayed for a period of time before the task can be Executed. This is not a bug, but an optimization of the power consumption of the System. The system automatically detects how many Alarm tasks are currently present, and then executes a few tasks that have triggered time, which can significantly reduce the number of times the CPU wakes up, effectively prolonging battery life.</p></p><p><p>of course, Android still offers a solution if you require that the Alarm Task's execution time must be prepared correctly. By using Alarmmanager's setexact () method instead of the set () method, the task is guaranteed to execute on Time.</p></p><p><p>Android: timed tasks performed in the background</p></p></span>
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