我有一个在开机时启动的更新服务。问题是我希望它进行检查,然后等待一段时间并自行重启。当我的服务绑定(bind)到一个应用程序时,我用闹钟做了这个,但现在它是独立的,我只使用广播接收器在启动时启动它。问题是现在出于某种原因我无法将我的闹钟与它集成。 我只有我的 UpdateService 类和我的 broadcastreceiver 类。到目前为止我在 broadcastreceiver 中的代码是这样的,但我想把闹钟放在这里说安排服务每 30 秒启动一次。我真的需要这个。
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, UpdateService.class);
context.startService(startServiceIntent);
}
欢迎提出任何建议。提前致谢。
最佳答案
我找到了问题的答案:
private boolean service_started=false;
private PendingIntent mAlarmSender;
@Override
public void onReceive(Context context, Intent intent) {
if(!service_started){
// Create an IntentSender that will launch our service, to be scheduled
// with the alarm manager.
mAlarmSender = PendingIntent.getService(context,
0, new Intent(context, UpdateService.class), 0);
//We want the alarm to go off 30 secs from now.
long firstTime = SystemClock.elapsedRealtime();
// Schedule the alarm!
AlarmManager am = (AlarmManager)context.getSystemService(context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime,30*1000, mAlarmSender);
service_started=true;
}
}
最终,我的问题是我没有得到如下正确的上下文:
(AlarmManager)getSystemService(ALARM_SERVICE);
改为 (AlarmManager)context.getSystemService(context.ALARM_SERVICE);
关于android - 使用定时器/闹钟启动时更新服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7950694/