准确地在小时开始服务,然后每小时重复一次

时间:2012-01-11 12:47:34

标签: android alarmmanager repeat

我希望在每小时开始的时候开始一个IntentService,这个小时在一小时(下午1点,下午2点,下午3点等)完全重复。

查看了文档后,我相信使用AlarmManager执行此操作是最佳做法。

我有一个BootReceiver,它将启动第一个实例的应用程序,并在我的onHandleIntent下面,在重复任务后设置下一个警报(例如下面的振动)。我的问题是我无法将警报设置为在下一个小时的顶部关闭,我将如何解决这个问题?

为了进行测试,我在下面的代码中每隔3分钟发出警报

public class TimingAndControl extends IntentService
{ public TimingAndControl()
{
super(TimingAndControl.class.getSimpleName());
}

@Override
protected void onHandleIntent(Intent intent)
{  
  PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
  PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK |       PowerManager.ACQUIRE_CAUSES_WAKEUP, "VibrateTag");
  wakeLock.acquire();

  Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

  v.vibrate(300);

  NextAlarm();
}

private void NextAlarm()
{
Intent intent = new Intent(this, this.getClass());
PendingIntent pendingIntent =
    PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// The update frequency should often be user configurable.  This is not.

long currentTimeMillis = System.currentTimeMillis();
long nextUpdateTimeMillis = currentTimeMillis + 3 * (60 * 1000);
Time nextUpdateTime = new Time();
nextUpdateTime.set(nextUpdateTimeMillis);

if (nextUpdateTime.hour < 6 || nextUpdateTime.hour >= 18)
{
  nextUpdateTime.hour = 8;
  nextUpdateTime.minute = 0;
  nextUpdateTime.second = 0;
  nextUpdateTimeMillis = nextUpdateTime.toMillis(false) + DateUtils.DAY_IN_MILLIS;
}
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
}
@Override
public void onCreate(){
    Toast.makeText(this, "service starting", (10 * 1000)).show();
    super.onCreate();

}

@Override
public void onDestroy() {
  Toast.makeText(this, "service stopping", (10 * 1000)).show();
  super.onDestroy();
} 



}

3 个答案:

答案 0 :(得分:0)

您是否尝试过RTC_WAKEUP,只有在器件从休眠模式唤醒后,RTC标志才会触发报警。

答案 1 :(得分:0)

  

我的问题是我无法将警报设置为在下一个小时的顶部发出警报,我该如何处理呢?

计算下一个小时的顶部时间,然后将其用作setRepeating()AlarmManager的第二个参数。

答案 2 :(得分:0)

您可以使用此代码(未测试)

找到下一小时的UTC毫秒时间
public static final long utcMillisNextHour() {
    Time t = new Time();
    t.setToNow();
    t.hour++;
    t.minute = 0;
    t.second = 0;
    return t.normalize(true);
}

然后,您可以使用AlarmManager的setReapting ..()方法之一,其时间类型接受UTC时间和INTERVAL_HOUR间隔。如果您发送的意图是固定的,那么多次调用它并不会造成伤害,因为每个setRepeating()都会删除之前的意图。

相关问题