postDelayed()的服务 [英] postDelayed() in a Service

查看:225
本文介绍了postDelayed()的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在几个时间从自身重新启动服务。我的code看起来像这样(在 onStartCommand(...)

I'm trying to restart service from itself in a few time. My code looks like this (inside the 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);

服务在前台运行时,该code执行,但它似乎并没有叫 onStartCommand(...)
是否有任何其他方式在短短的时间从自身重新启动服务?

Service is running in the foreground while this code executes, but it doesn't seem to call onStartCommand(...) . Is there any other way to restart service from itself in a few time?

UPD:我发现,它实际上重新启动服务,而不是在一个给定的时间(可能需要长达30分钟,而不是给出3)。所以,现在的问题是如何使它重新启动因而

UPD: I've found out that it actually restarts service, but not in a given time (may take up to 30 minutes instead of given 3). So now the question is how to make it restart consequently

推荐答案

由处理器调度操作不能始终如一地运行,因为该设备可能在此刻睡觉。安排背景中的任何延迟作用的最好的方法是使用系统AlarmManager。结果
在此情况下,code必须具有下列取代:

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

这篇关于postDelayed()的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆