I need a periodic task that require internet connection and persists after reboots. I have achieved that much but the problem is that I want the app to continue working even adter I exit it.
As in, if I exist the app and turn off wifi and then turn it back again (and if the period is up) then the task should be triggered and work in the background.
This is the startPeriodicTask method
public void startPeriodicTask() {
Log.d(TAG, "startPeriodicTask");
// [START start_periodic_task]
PeriodicTask task = new PeriodicTask.Builder()
.setService(MyTaskService.class)
.setTag(TASK_TAG_PERIODIC)
.setPeriod(30L)
.setPersisted(true) // to persist after reboot
.setRequiredNetwork(Task.NETWORK_STATE_ANY )
.build();
mGcmNetworkManager.schedule(task);
// [END start_periodic_task]
}
and I just call this method in the OnCreate right after checking for playServices
checkPlayServicesAvailable();
startPeriodicTask();
I've added this to manifest in order for the job to persist after reboot
<uses-permission android:name="android.Manifest.permission.RECEIVE_BOOT_COMPLETED" />
The only way to have a task start again after the wifi comes back on is to call it from a Receiver. So you need to create a receiver that gets called when the network state changes. Then inside this you can check if it's on or off. If it's on, then call your method.
You can see exactly how to do this in the sample at the bottom of this documentation page: https://developer.android.com/training/basics/network-ops/managing.html