In android, you can use various methods to start a periodic background task, and some of them:
- JobScheduler (API 21 or later only)
Android added this class in API 21 for a link here documentation.
- JobSchedulerCompat - Backport of JobScheduler library for API 11 or higher
Here you can find everything about the library.
- Use the alarm manager to handle a periodic task
You can also use AlarmManager to schedule a periodic task. The full article for its implementation is available here .
- Use CloudMicro Network Manager (Google Cloud Messaging) to schedule a recurring task.
You can see this link for its implementation.
Example for a periodic task using the GCM network manager
Add a dependency at the project level build.gradle.
compile 'com.google.android.gms:play-services-gcm:7.5.0'
Create a java class that extends to GcmTaskService
public class BackgroundTaskHandler extends GcmTaskService { public BackgroundTaskHandler() { } @Override public int onRunTask(TaskParams taskParams) {
Declare a service in manifest.xml
<service android:name=".BackgroundTaskHandler" android:exported="true" android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE"> <intent-filter> <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" /> </intent-filter> </service>
Now we plan a periodic task from any class as: -
String tag = "periodic"; GcmNetworkManager mScheduler = GcmNetworkManager.getInstance(getApplicationContext()); long periodSecs = 60L;// 1 minute PeriodicTask periodic = new PeriodicTask.Builder() .setService(BackgroundTaskHandler.class) .setPeriod(periodSecs) .setTag(tag) .setPersisted(true) .setUpdateCurrent(true).setRequiredNetwork(com.google.android.gms.gcm.Task.NETWORK_STATE_CONNECTED) .build(); mScheduler.schedule(periodic);
Aawaz gyawali
source share