postDelayed() in a Service

前端 未结 3 364
我寻月下人不归
我寻月下人不归 2021-01-12 17:36

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

Looper.prepare();
Handler han         


        
相关标签:
3条回答
  • 2021-01-12 17:55

    Actions scheduled by handler can't be run consistently because the device might be sleeping at the moment. The best way to schedule any delayed action in the background is to use system AlarmManager

    In this case, code must be replaced with 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);
    
    0 讨论(0)
  • 2021-01-12 18:09

    Replace

    Handler handler = new Handler();
    

    With

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

    Worked for me.

    0 讨论(0)
  • 2021-01-12 18:17

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

    0 讨论(0)
提交回复
热议问题