Problem with ScheduledExecutorService when running in Android service

1

One question, I'm creating a service on android, and I need this one to call a method every so often, and for that I'm using ScheduledExecutorService . Here I put the code:

@Override
    public int onStartCommand(Intent intent, int flags, int startId){ //Método donde se ejecuta el código que tiene que hacer el servicio
        Toast.makeText(getApplicationContext(), "Servicio iniciado correctamente", Toast.LENGTH_LONG).show(); //mostrar una notificación de servicio iniciado

      final Runnable ejecucion = new Runnable() {
                public void run() {
                    Servicio(); //método que llamo cada 10 segundos
                }
            };
            ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
            timer.scheduleAtFixedRate(ejecucion, 10, 10, TimeUnit.SECONDS);

        return START_STICKY;
    }

The problem is that the method is called only once, when I need to do it at intervals that I already put in, investigating several ways to do it, I run into the same problem, which leads me to think that I am omitting something.

    
asked by Juan Trinidad Mayo 06.10.2017 в 01:15
source

1 answer

1

The code you show to perform a task every x seconds using ScheduledExecutorService , I assure you has no problem, will call every 10 seconds the method Servicio() , the problem is within this method.

 final Runnable ejecucion = new Runnable() {
                public void run() {
                    Servicio(); //método que llamo cada 10 segundos
                }
            };
            ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
            timer.scheduleAtFixedRate(ejecucion, 10, 10, TimeUnit.SECONDS);

Add your Servicio() method and what it displays in the LogCat when stopped.

    
answered by 06.10.2017 в 01:43