8

I want to run some code every day (every 24 hours). Problem is if user doesn't open app. How to run code when the application isn't open?

Mate Matenson
  • 93
  • 1
  • 5
  • 3
    http://stackoverflow.com/questions/2333680/android-schedule-action – nKn Aug 28 '15 at 16:12
  • possible duplicate of [Setting android alarm manager on certain days](http://stackoverflow.com/questions/5715940/setting-android-alarm-manager-on-certain-days) – Ankit Aug 28 '15 at 16:36

2 Answers2

15

In android to run background periodic task you can use various ways and some of them are:

  1. JobScheduler (Only for API 21 or above)

Android has added this class on API 21 for documentation here is the link.

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

You can find everything about library here.

  1. Use alarm manager to handle periodic task

You can also use AlarmManager to schedule periodic task. A full article to implement it is posted here.

  1. Use GCM(Google Cloud Messaging) Network Manager to schedule periodic task.

You can have a look at this docs link to implement it.

Example for periodic Task using GCM Network Manager

Add dependency in your project level build.gradle.

compile 'com.google.android.gms:play-services-gcm:7.5.0'

Create a java class that extends toGcmTaskService

public class BackgroundTaskHandler extends GcmTaskService {

    public BackgroundTaskHandler() {
    }

    @Override
    public int onRunTask(TaskParams taskParams) {
         //Your periodic code here
    }
}

Declare the 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 schedule the 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
  • 3,244
  • 5
  • 28
  • 48
1

The brand new way to implement scheduled operations is to use job scheduler, which is available from sdk level 21.

A simpler (and backported) way to perform periodic tasks has been (not so) recently added to google play services : network manager. Despite of its name, it is useful to schedule non network related tasks.

Check the

Schedule a periodic task regardless of network and device charging states

section.

fedepaol
  • 6,834
  • 3
  • 27
  • 34