BootCompletedReceiver在啓動時運行後臺服務,因此生命週期的通知在運行時在通知欄中顯示。當我從通知欄中刪除通知時,我希望在15分鐘後看到它,但我不知道,它隨機出現。每15分鐘啓動一次通知的報警管理器
我的代碼有什麼問題?
public class BootCompletedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, BirthdayNotifyService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
context.startService(serviceIntent);
setAlarm(context, pendingIntent);
}
private void setAlarm(Context context, PendingIntent pendingIntent) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), 1000 * 60 * 2, pendingIntent);
}
public class BirthdayNotifyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotifications();
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotifications() {
// Fetching contacts from the Contacts application
ArrayList<MyContact> contactsList = BirthdayDataFactory.getContacts(this);
// Going trough the contacts list and creating notifications for each contact that has birthday
for (int i = 0; i<contactsList.size(); i++) {
if(contactsList.get(i).hasBirthday()) {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Creating a notification builder
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Birthday Notifier")
.setContentText(contactsList.get(i).getName() + " has a Birthday today!")
.setContentIntent(pendingIntent);
// Creating a notification manager
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(i, builder.build());
}
}
}
}