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?
you can use onAppForegroundStateChange() method which call when app is open and closed. this method is only called when your app comes in foreground/background. onAppForegroundStateChange() method is better then you used onPause() method because onPause method is also called every time when you go to other activity.
Recommended solutionScheduling deferred work through WorkManager is the best way to handle tasks that don't need to run immediately but which ought to remain scheduled when the app closes or the device restarts.
Just check for some preference with default value indicating that it's a first run. So if you get default value, do your initialization and set this preference to different value to indicate that the app is initialized already.
In android to run background periodic task you can use various ways and some of them are:
Android has added this class on API 21 for documentation here is the link.
You can find everything about library here.
You can also use AlarmManager
to schedule periodic task. A full article to implement it is posted here.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With