Run the code every day when the application does not open

I want to run the code every day (every 24 hours). The problem is that the user does not open the application. How to run code when the application is not open?

+7
android
source share
2 answers

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.

  1. JobSchedulerCompat - Backport of JobScheduler library for API 11 or higher

Here you can find everything about the library.

  1. 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 .

  1. 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) { //Your periodic code here } } 

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); 
+10
source share

A completely new way to implement planned operations is to use the task scheduler , available from sdk level 21.

A simpler (and vice versa) way to perform periodic tasks was (not quite) recently added to google play services: network manager . Despite its name, it’s useful to plan non-network tasks.

Check out

Schedule a periodic task regardless of the state of charge of the network and device.

section.

+1
source share

All Articles