Android AlarmManager Realizes Timing Loop Background Task
- 2021-11-10 10:41:17
- OfStack
This article uses AlarmManager to implement the Android timing background loop task. Usage scenario: The project requires app to go to the server to request the interface once every 1 period of time, so as to update the locally saved information.
Introduction to AlarmManager
AlarmManager is a system-level prompt service commonly used in Android, which broadcasts a specified Intent for us at a specific time. Simply put, we set a time, and then when that time comes, AlarmManager broadcasts us an Intent that we set, usually we use PendingIntent.
Brief introduction of project functions:
AlarmService simulates background tasks and broadcasts regularly AlarmReceive starts AlarmService to achieve the effect of cyclically starting ServiceThrough the dead loop of Service and Receiver, ensure that background tasks are not killed by the system.
1. AlarmService class
/**
* 1 Timed tasks
*/
public class AlarmService extends Service {
/**
* Every 1 Minute update 1 Secondary data
*/
private static final int ONE_Miniute=60*1000;
private static final int PENDING_REQUEST=0;
public AlarmService() {
}
/**
* Call Service Will execute to the method
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The background operation is simulated here
new Thread(new Runnable() {
@Override
public void run() {
Log.e("wj"," The loop is executed, haha ."+ System.currentTimeMillis());
}
}).start();
// Pass AlarmManager Start broadcasting regularly
AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
long triggerAtTime=SystemClock.elapsedRealtime()+ONE_Miniute;// Millisecond book from boot to present (cell phone sleep (sleep) The time of is also included
Intent i=new Intent(this, AlarmReceive.class);
PendingIntent pIntent=PendingIntent.getBroadcast(this,PENDING_REQUEST,i,PENDING_REQUEST);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pIntent);
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
2 AlarmReceive class
public class AlarmReceive extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// Loop start Service
Intent i = new Intent(context, AlarmService.class);
context.startService(i);
}
}
3 Start Service
public void startService(View view){
Intent intent=new Intent(this, AlarmService.class);
startService(intent);
}
Don't forget to register broadcasts and services in AndroidMainfest:
<service
android:name=".service.AlarmService"
android:enabled="true"
android:exported="true"/>
<receiver android:name=".receive.AlarmReceive"/>