postDelayed() in a Service

北城余情 提交于 2019-12-01 04:28:03

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

Bolein95

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

Replace

Handler handler = new Handler();

With

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

Worked for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!