今回は、AlarmManagerで定期的にServiceを実行するメモです。
AlarmManager でサービスを登録
- ServiceのIntentを作成します。
- Serviceを開始するPendingIntentを取得します。
- AlarmManager#setInexactRepeatingでアラームをスケジュールします。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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 でサービスを解除
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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の登録状態を確認
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
# 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
0 件のコメント:
コメントを投稿