How to stop the service some time after its launch. Suppose the service has worked for a minute, now you have to kill it.

    1 answer 1

    Try this: what you write in "run" will be executed in the number of milliseconds specified by the number at the end of the method.

    final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // Сделать что-то чрез 60с = 60 000мс //Тут останавливать сервис context.stopService(new Intent(context, Service.class)); } }, 60000); 

    Respectively place this piece of code in the method that runs when the service starts.

    • one
      Stop - context.stopService (new Intent (context, Service.class)); - Rammsteinik
    • @Rammsteinik Updated the answer. - Yuriy SPb
    • But postDelayed does not guarantee performance after a long period of time. Better to use AlarmManager. Or stop through postDelayed yourself (ie, write it inside the service) - Deadkenny
    • And if the main thread will be busy with something heavy? Of course this should not be but all the same? In general, I am inclined that the topic of the starter has an ugly program design. - arg
    • @argamidon And if this code is placed in AsynkTask, which one will be launched when the service starts? - Yuriy SPb