服务中的 postDelayed()

postDelayed() in a Service

我正在尝试在一段时间后自行重启服务。我的代码看起来像这样(在 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);

服务在前台 运行 执行此代码时,但它似乎没有调用 onStartCommand(...) 。 有没有其他方法可以在一段时间内自行重启服务?

UPD:我发现它实际上会重新启动服务,但不是在给定的时间内(最多可能需要 30 分钟,而不是给定的 3 分钟)。所以现在的问题是如何让它重启

处理程序安排的操作不能运行一致,因为设备此时可能正在休眠。在后台安排任何延迟操作的最佳方法是使用系统 AlarmManager

在这种情况下,代码必须替换为以下内容:

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

我会在服务级别声明 Handler 变量,而不是在 onStartCommand 中本地声明,例如:

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

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

而且服务有自己的循环,所以你不需要Looper.prepare();

替换

Handler handler = new Handler();

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

对我有用。