Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postDelayed() in a Service

I'm trying to restart service from itself in a few time. My code looks like this (inside the onStartCommand(...))

Looper.prepare();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(BackgroundService.this, BackgroundService.class);
                startService(intent);
            }
        }, 3 * 60000);

Service is running in the foreground while this code executes, but it doesn't seem to call onStartCommand(...) . Is there any other way to restart service from itself in a few time?

UPD: I've found out that it actually restarts service, but not in a given time (may take up to 30 minutes instead of given 3). So now the question is how to make it restart consequently

like image 826
Bolein95 Avatar asked Apr 29 '15 10:04

Bolein95


2 Answers

I would declare the Handler variable at the Service level, not locally in the onStartCommand, like:

public class NLService extends NotificationListenerService {
    Handler handler = new Handler(); 

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handler.postDelayed(new Runnable() {....} , 60000);
    }

And the service has its own loop, so you do not need Looper.prepare();

like image 136
geekQ Avatar answered Sep 19 '22 13:09

geekQ


Replace

Handler handler = new Handler();

With

Handler handler = new Handler(Looper.getMainLooper());

Worked for me.

like image 42
Matt W Avatar answered Sep 20 '22 13:09

Matt W