在我的应用程序中,我在ACTION_BOOT_COMPLETED Intent 上注册了一个广播接收器,以便在设备启动完成时收到通知。
要获得结果,您必须在清单文件中指定以下内容:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
...
<receiver
android:name=".YOUR_BROADCAST_RECEIVER">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
在 BroadcastReceiver 中,我使用
启动了服务
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, serviceClass));
...
}
终于在服务的onStartCommand中
public int onStartCommand(Intent intent, int flags, int startId) {
...
setNextSchedule();
...
}
private void setNextSchedule() {
long time = WHEN_YOU WANT_THE SERVICE TO BE SCHEDULED AGAIN;
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(this, 0,new Intent(this, this.getClass()), PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, time, pi);
}
AlarmManger 将使用待处理的 Intent 将您传递的 Intent 发送到您的服务。看看here
再见