AlarmManagerで指定した時間に処理させる


AndroidにはAlarmManagerというしくみがあります。
AlarmManagerを使うことで指定した時間に任意の処理をさせることができます。

詳しくは続きからご覧下さい。

AlarmManagerのメソッドは主に以下のようなものがあります。

void cancel(PendingIntent operation) 処理を削除
void set(int type, long triggerAtTime, PendingIntent operation) 任意の時間で実行する処理を登録
void setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation) 一定間隔で実行する処理を登録

上記のように、任意の時間に任意の処理を登録するにはsetメソッドを使います。

setメソッドの第1引数には第2引数で指定する起動時間をどのように設定するかを指定します。
代表的なものに以下の定数が定義されています。

ELAPSED_REALTIME 電源ONからの経過時間で指定
ELAPSED_REALTIME_WAKEUP 電源ONからの経過時間で指定。スリープ状態のときは電源をONにしてくれる
RTC UTC時刻で指定
RTC_WAKEUP UTC時刻で指定。スリープ状態のときは電源をONにしてくれる

具体的なコードは以下のようになります。

Intent i = new Intent(getApplicationContext(), ReceivedActivity.class); // ReceivedActivityを呼び出すインテントを作成
PendingIntent sender = PendingIntent.getBroadcast(AlarmSample.this, 0, i, 0); // ブロードキャストを投げるPendingIntentの作成

Calendar calendar = Calendar.getInstance(); // Calendar取得
calendar.setTimeInMillis(System.currentTimeMillis()); // 現在時刻を取得
calendar.add(Calendar.SECOND, 15); // 現時刻より15秒後を設定

AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); // AlramManager取得
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender); // AlramManagerにPendingIntentを登録

ブロードキャストを投げるPendingIntentを作成しAlermManagerに登録しています。
(PendingIntentについては「AppWidgetの作成(2) + PendingIntent」で取り上げられています)
登録後、15秒が経過したらインテントで指定しているReceivedActivityが実行されます。

受け手となるReceivedActivityは呼び出されたときにToastを表示します。

public class ReceivedActivity extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context, "called ReceivedActivity", Toast.LENGTH_SHORT).show();
    }
}

なお、AndroidManifestにBroadcastReceiverを有効にするための記述をAndroidManifestに記述しておく必要があります。

<receiver android:name=".ReceivedActivity" android:process=":remote" />
One Comment