我正试图在几个时间内重新启动服务本身。我的代码看起来如下(在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分钟)。所以现在的问题是如何使它重新启动。
发布于 2015-04-29 18:20:24
处理程序计划的操作不能一致地运行,因为设备目前可能正在休眠。在后台安排任何延迟操作的最佳方法是使用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);发布于 2016-07-14 09:50:24
我将在服务级别声明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();。
发布于 2017-06-27 23:01:45
替换
Handler handler = new Handler();使用
Handler handler = new Handler(Looper.getMainLooper());为我工作过。
https://stackoverflow.com/questions/29941267
复制相似问题