android - 使用定时器/闹钟启动时更新服务

标签 android service broadcastreceiver alarmmanager boot

我有一个在开机时启动的更新服务。问题是我希望它进行检查,然后等待一段时间并自行重启。当我的服务绑定(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/

相关文章:

android - 为什么 Media Player 找不到我的 SD 卡的 URI?

java - sbt:对象应用程序不是包的成员

android - 通话录音/处理服务! - 安卓

Android 服务对位置更改执行操作

Android设置自定义标题栏高度

java - 确定某些字体在android中是否可用?

java - 在 BroadcastReceiver() 中检索调用上下文

android - 不允许后台执行接收 Intent BOOT_COMPLETED

java - 线程中的服务与服务中的线程

sdcard的android Intent 准备好了