创建一个广播接收器或意图服务。然后...
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 中重新创建警报。
编辑
当你在你的应用程序中创建一个 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 操作,因此您的接收器也会在发生这种情况时被调用。