AlarmManagerを使って一定時間後に処理を行う
最終更新日:2015-09-05
AlarmManagerを使って一定時間後に何か処理をするには、次の3ステップを行います。
- 処理を記述したServiceを作る
 - 
PendingIntentを作る - 
set()でアラームをセットする 
順にみていきましょう。
処理を記述したServiceを作る
まず、Serviceを1つ作ります。ここではToastを表示するだけのServiceとしました。
public class MessageService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String text = intent.getStringExtra(Intent.EXTRA_TEXT);
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
        return Service.START_NOT_STICKY;
    }
}
PendingIntentを作る
次に、アプリ側でPendingIntentを作ります。先ほど作成したServiceを起動するIntentを元に作ります。
Intent it = new Intent(context, MessageService.class);
it.putExtra(Intent.EXTRA_TEXT, message);
int requestCode = 1;
PendingIntent pendingIntent = PendingIntent.getService(context, requestCode, it, PendingIntent.FLAG_UPDATE_CURRENT);
set()でアラームをセットする
PendingIntentの作成までできたら、最後にAlarmManagerのset()でアラームをセットします。アラームという名称ですが音がなったりするわけではありません。
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.ELAPSED_REALTIME, 3000, pendingIntent);
第1引数にはどのタイミングでPendingIntentを実行するかを指定します。ここでは指定した時間が過ぎた後としたいので、AlarmManager.ELAPSED_REALTIMEを指定します。第2引数は何ミリ秒後に実行するかを指定します。ここでは3000を指定したので3秒後に実行されます。第3引数には実行するPendingIntentを指定します。

