2011年6月25日土曜日

AlarmManagerで定期的に繰り返しサービスを実行する

一定時間に処理を実行したり、定期的に処理を繰り返すにはAlarmManagerを使用します。
今回は、AlarmManagerで定期的にServiceを実行するメモです。


AlarmManager でサービスを登録
  1. ServiceのIntentを作成します。
  2. Serviceを開始するPendingIntentを取得します。
  3. AlarmManager#setInexactRepeatingでアラームをスケジュールします。
Intent serviceIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent
= PendingIntent.getService(this, 0, serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setInexactRepeating (
AlarmManager.RTC,
System.currentTimeMillis(),
//AlarmManager.INTERVAL_HOUR,
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent);

AlarmManager.RTC - wall-clock timew in UTC 要は現実世界での経過時間
AlarmManager.INTERVAL_FIFTEEN_MINUTES - 15分(900000秒) Intervalの定数


AlarmManager でサービスを解除
Intent serviceIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent
= PendingIntent.getService(this, 0, serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pendingIntent);


adb コマンドで、AlarmManagerの登録状態を確認
# adb shell dumpsys alarm
Current Alarm Manager state:
Realtime wakeup (now=1308812542789):
RTC #2: Alarm{487c9590 type 1 net.granoeste.example.repeatedlyrunning}
type=1 when=1308813378896 repeatInterval=900000 count=1
operation=PendingIntent{487f4ac0: PendingIntentRecord{487bb340 net.granoeste.example.repeatedlyrunning startService}}
Elapsed realtime wakeup (now=620467383):
Broadcast ref count: 0
Alarm Stats:
net.granoeste.example.repeatedlyrunning
44ms running, 0 wakeups
1 alarms: flg=0x4 cmp=net.granoeste.example.repeatedlyrunning/.MyService
view raw dumpsys alarm hosted with ❤ by GitHub

0 件のコメント:

コメントを投稿