Android 服务中的postDelayed()

Android 服务中的postDelayed(),android,android-service,android-handler,Android,Android Service,Android Handler,我正在尝试在几分钟内从自身重新启动服务。我的代码如下所示(在onstart命令(…)中) 此代码执行时,服务正在前台运行,但它似乎没有调用onStartCommand(…)。 有没有其他方法可以在几分钟内从自身重新启动服务 UPD:我发现它实际上会重新启动服务,但不是在给定的时间内(可能需要30分钟而不是给定的3分钟)。因此,现在的问题是如何使其重新启动,因此处理程序安排的操作无法一致地运行,因为此时设备可能正在休眠。在后台计划任何延迟操作的最佳方法是使用system AlarmManager

我正在尝试在几分钟内从自身重新启动服务。我的代码如下所示(在
onstart命令(…)
中)

此代码执行时,服务正在前台运行,但它似乎没有调用
onStartCommand(…)
。 有没有其他方法可以在几分钟内从自身重新启动服务


UPD:我发现它实际上会重新启动服务,但不是在给定的时间内(可能需要30分钟而不是给定的3分钟)。因此,现在的问题是如何使其重新启动,因此处理程序安排的操作无法一致地运行,因为此时设备可能正在休眠。在后台计划任何延迟操作的最佳方法是使用system 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);

我将在服务级别声明处理程序变量,而不是在onstart命令中本地声明,如:

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();
Handler handler = new Handler(Looper.getMainLooper());