创建广播接收器或意图服务。然后...
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"/>
作为清单中接收器上的意图过滤器,并在 onReceive 中重新创建警报。
EDIT
当您在应用程序中创建 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>
在清单中包含此内容可以为您带来两件事:您可以随时通过以下方式显式向接收者发送广播
Intent i = new Intent("SOME_AWESOME_TRIGGER_WORD");
sendBroadcast(intent);
另外,由于您已经告诉 android 您希望接收系统广播的 BOOT_COMPLETED 操作,因此当发生这种情况时,您的接收器也会被调用。