Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Android runs in the background and triggers tasks regularly.
Android runs in the background and triggers tasks regularly.
There are generally two ways to realize timed tasks in Android, one is to use Java.

The Timer class in API, and the other is to use the alarm mechanism of Android.

These two methods can achieve similar results in most cases, but Timer has an obvious disadvantage and is not suitable for those timing tasks that need to run in the background for a long time. Because we

You know, in order to make the battery more durable, each mobile phone will have its own sleep strategy: for example, when the mobile phone is not in use, it will intelligently disconnect the wifi connection, automatically adjust the screen brightness according to the light intensity, and automatically put the CPU into sleep according to the long-term inactivity of the mobile phone. When it enters the sleep state, it may cause the timing task in the timer to fail to run normally. But this is not the case with Alarn mechanism. It has the function of waking up the CPU, that is, it can ensure that the CPU can work normally every time it needs to perform a predetermined task. It should be noted that the wake-up CPU and wake-up screen here are not the same concept and cannot be confused.

Here we only talk about the way of alarm mechanism, and the code is as follows:

Public class AutoUpdateService extension service {

@ Overlay

Public IBinder onBind (intention) {

Returns null

}

//Called every time the service starts.

@ Overlay

public int onstart command(Intent Intent,int flags,int startId) {

New thread (new Runnable() {

@ Overlay

Public invalid operation () {

do something(); //This is a task performed by the timer.

}

}).start();

ALARM manager manager =(ALARM manager)getsystem SERVICE(ALARM _ SERVICE);

int anHour = 8 * 60 * 60 * 1000; //This is 8-hour milliseconds. In order to reduce traffic and power consumption, it is automatically updated every 8 hours.

long trigger attime = system clock . elapsedrealtime()+an hour;

Intent intent2 = new Intent(this,autoupdatereceiver . class);

pending intent pi = pending intent . get broadcast(this,0,intent2,0);

manager.set(AlarmManager。 ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi); & lt/span>。

Returns super. onstartcommand (intention, flags, startid);

}

Note that alarm manager = (alarm manager) get system service (alarm _ service) here; The timing task is realized here.

First, we get an instance of AlarmManager by calling the getSystemService () method of Context. The parameter to be passed in here is ALARM_SERVICE.

Next, you can set a scheduled task by calling the set () method of AlarmManager. For example, setting a task to be executed after 5 seconds can be written as long.

trigger attime = system clock . elapsedrealtime()+5 * 1000;

manager.set(AlarmManager。 ELAPSED_REALTIME_WAKEUP, trigger time,

pi);

The first parameter is an integer parameter, which is used to specify the work type of AlarmManager. There are four values to choose from, namely

ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC and RTC_WAKEUP. Where ELAPSED_REALTIME means that the trigger time of the timing task is calculated from the system startup, but it will not wake up the CPU. ELAPSED_REALTIME_WAKEUP also means that the trigger time of the timed task is calculated from the system startup, but it will wake up the CPU. When RTC is specified, the trigger time of the task will start from 0: 00 on June 1970 1 day, but it will not wake up the CPU. RTC_WAKEUP also means that the trigger time of the scheduled task starts from 0: 00 on June 1970 1 day, but it will wake up the CPU. The method of SystemClock.elapsedRealtime () can be used to obtain the millisecond time since the system started, and the method of System.currentTimeMillis () can be used to obtain the millisecond time since 0: 00 on June 1970+ 1 day.

Then look at the second parameter, which is much easier to understand, that is, the time when the scheduled task is triggered, in milliseconds. If the first parameter is ELAPSED_REALTIME or ELAPSED_REALTIME_WAKEUP, the time from startup plus the time of delayed execution will be passed here. If RTC or RTC_WAKEUP is used as the first parameter,1970 1:001October1:00 is passed in here.

The third parameter is PendingIntent, where we usually call the getBroadcast () method to get a PendingIntent that can perform broadcasting. In this way, when the timing task is triggered, the onReceive () method of the broadcast receiver can be executed.

Of course, setting a task to be executed after 10 seconds can also be written as:

longtriggerAtTime =

system . current time millis()+ 10 * 1000;

manager.set(AlarmManager。 RTC_WAKEUP,triggerAtTime,

pendingIntent);

Then create a PendingIntent to specify the broadcast receiver AutoUpdateReceiver that handles the scheduled task.

Import services. AutoUpdateService

Import android.content.broadcastreceiver;

Import android.content.context;

Import android.content.intent;

Public class AutoUpdateReceiver extends BroadcastReceiver {

@ Overlay

Public void onReceive (context, intention) (

Intent i = new Intent(context,autoupdateservice . class);

context . start service(I);

}

}

When the AutoUpdateService is started, a timed task will be set in the onStartCommand () method, so that the onReceive () method of the AutoUpdateReceiver will be executed every 8 hours, and the AutoUpdateService will be started again, forming a permanent cycle to ensure that the service is started every once in a while, thus completing a service that runs in the background for a long time.

Where do we start the service? It depends on the specific situation. Generally speaking, we only start the program once when we open it.

For example, it is written in the onCrete () method of Activity.

purpose

intent =new Intent(this,auto updateservice . class);

StartService (intention);

Finally, because we use services and broadcast receivers, we must register in AndroidManifest.xml

& lt service android:name="service. AutoUpdateService " >& lt/service & gt;

& lt receiver android:name="receiver. Automatic update receiver "

& gt& lt/receiver & gt;

References for this article:

The first line of code