I want to use a service that run in background indefinitely and call a method every 10 minute and its running even app killed
How to create it?
Create a Timer object and give it a TimerTask that performs the code you'd like to perform. The advantage of using a Timer object is that it can handle multiple TimerTask objects, each with their own timing, delay, etc.
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.
onStartCommand() The system invokes this method by calling startService() when another component (such as an activity) requests that the service be started. When this method executes, the service is started and can run in the background indefinitely.
You can do by using service as follows
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//performe the deskred task
}
}, 10minutes time in milisecods);
// If we get killed, after returning from here, restart
return START_STICKY;
}
This service will get started automatically even if app get killed, and postdelayed will run
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