Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run service in background every 10 minute?

Tags:

android

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?

like image 725
Alireza milani Avatar asked Jan 21 '15 08:01

Alireza milani


People also ask

How do I get service to run every 5 minutes?

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.

What is the current recommend way to handle long-running background tasks?

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.

How do I start a background service?

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.


1 Answers

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

like image 100
Ichigo Kurosaki Avatar answered Oct 29 '22 00:10

Ichigo Kurosaki