Run a service every certain amount of time

0

My query is as follows. I am trying to perform a service that shows a message in the LogCat every 1 minute for example. I was reading a bit about this but I think I need a hand. The services always work when the phone is with the screen off / or in background? How should I call the service again after one minute? I have the code now:

public class MiServicio extends Service{

  public IBinder onBind(Intent intent) {
        return null;
  }
}

public void onCreate(){
  super.onCreate();
}

public void onStart(Intent intent, int startId){
  Log.d("MiServicio", "Servicio corriendo...");
  // Este es el mensaje que quiero mostrar cada minuto como prueba
}

public void onDestroy(){
  super.onDestroy();
  Log.d("MiServicio", "El Servicio se detuvo.");
}

I have it declared to start on my MainActivity like this:

startService(new Intent(MainActivity.this, MiServicio.class));

I have read that I must use a TimerTask but I do not have much idea of how to initialize everything in my service. I guess it must be on the onStart. I would also like to know if it is convenient to stop the service sometime or it does not matter that it is always without stopping. Thanks in advance.

    
asked by Megaherx 29.04.2018 в 19:47
source

1 answer

1

It depends on the type of service you want to run although I recommend using JobDispatcher: link

It's as simple as:

Job myJob = dispatcher.newJobBuilder()
    .setService(MyJobService.class) // the JobService that will be called
    .setTag("my-unique-tag")        // uniquely identifies the job
    .build();

dispatcher.mustSchedule(myJob);
    
answered by 30.04.2018 в 00:28