ブロードキャストレシーバーまたはインテントサービスを作成します。それで...
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Date date = new Date(); //set this to some specific time
or Calendar calendar = Calendar.getInstance();
//set either of these to the correct date and time.
then
Intent intent = new Intent();
//set this to intent to your IntentService or BroadcastReceiver
//then...
PendingIntent alarmSender = PendingIntent.getService(context, requestCode, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
//or use PendingIntent.getBroadcast if you're gonna use a broadcast
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), mAlarmSender); // date.getTime to get millis if using Date directly.
電話を再起動してもこれらのアラームを正しく機能させるには、次を追加します。
<action android:name="android.intent.action.BOOT_COMPLETED"/>
マニフェストのReceiverのintentfilterとして、onReceiveでアラームを再作成します。
編集
アプリケーションでBroadcastReceiverを作成すると、システムでブロードキャストを受信するという、まさにそのように聞こえる操作を実行できます。たとえば、BroadcastReceiverは次のようになります。
public class MyAwesomeBroadcastReceiver extends BroadcastReceiver {
//since BroadcastReceiver is an abstract class, you must override the following:
public void onReceive(Context context, Intent intent) {
//this method gets called when this class receives a broadcast
}
}
このクラスにブロードキャストを明示的に送信するには、マニフェスト内で次のようにレシーバーを定義します。
<receiver android:name="com.foo.bar.MyAwesomeBroadcastReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="SOME_AWESOME_TRIGGER_WORD"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
これをマニフェストに含めると、2つのことが得られます。必要なときにいつでも受信者にブロードキャストを明示的に送信できます。
Intent i = new Intent("SOME_AWESOME_TRIGGER_WORD");
sendBroadcast(intent);
また、システムによってブロードキャストされるBOOT_COMPLETEDアクションを受信するようにAndroidに指示したため、それが発生するとレシーバーも呼び出されます。