PostDelayed () in the service

I am trying to restart the service from myself after a few seconds. My code looks like this (inside 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); 

The service runs in the foreground while this code is executing, but it does not seem to call onStartCommand(...) . Is there any other way to restart the service from myself after a few seconds?

UPD: I found out that it actually restarts the service, but not at a specific time (it can take up to 30 minutes instead of 3). So now the question is how to make it restart

+5
source share
3 answers

Actions scheduled by the handler cannot be performed sequentially because the device can sleep at the moment. The best way to schedule any slow motion in the background is to use the AlarmManager system.

In this case, the code should be replaced by the following:

 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent alarmIntent = new Intent(BackgroundService.this, BackgroundService.class); PendingIntent pendingIntent = PendingIntent.getService(BackgroundService.this, 1, alarmIntent, 0); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3 * 60, pendingIntent); 
+2
source

I would declare a Handler variable at the service level, and not locally in onStartCommand, for example:

 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();

+2
source

Replace

 Handler handler = new Handler(); 

FROM

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

Worked for me.

+1
source

All Articles