postDelayed()在服务中

Bol*_*n95 6 android android-service android-handler

我想在几次内重启服务.我的代码看起来像这样(里面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);
Run Code Online (Sandbox Code Playgroud)

此代码执行时,服务正在前台运行,但似乎没有调用onStartCommand(...).有没有其他方法可以在几次内重启服务?

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

gee*_*ekQ 5

我会在服务级别声明 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);
    }
Run Code Online (Sandbox Code Playgroud)

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


Bol*_*n95 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);
Run Code Online (Sandbox Code Playgroud)