Android 报警管理器,用于每15分钟启动一次通知
BootCompletedReceiver在启动时运行后台服务,因此在运行时通知栏中会显示生日通知。当我从通知栏中删除通知时,我希望在15分钟后看到它,但我没有,它是随机出现的 我的代码怎么了Android 报警管理器,用于每15分钟启动一次通知,android,service,notifications,alarmmanager,Android,Service,Notifications,Alarmmanager,BootCompletedReceiver在启动时运行后台服务,因此在运行时通知栏中会显示生日通知。当我从通知栏中删除通知时,我希望在15分钟后看到它,但我没有,它是随机出现的 我的代码怎么了 public class BootCompletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent serviceInten
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());
}
}
}
}
当我从通知栏中删除通知时,我希望看到
15分钟后
如果您希望发生这种情况,则不需要服务或重复报警
您应该做的jist是在NotificationBuilder上使用.setDeleteIntentIntent intent,传入一个intent,该intent将设置警报,以便在15分钟内再次运行通知代码,如下所示,而不是您当前在setAlarm中拥有的:
alarmManager.set(AlarmManager.ELAPSED_REALTIME, 1000*60*15, pendingIntent);
您当前在代码中执行的操作如下:
context.startServiceIntent;
立即启动显示通知的服务
设置AlarmContext,PendingContent
设置显示通知的报警,并立即触发,此后每2分钟触发一次
我建议您阅读更多关于您正在使用的每个方法/类的确切用途。您可以使用alarmManager.INTERVAL\u十五分钟,而不是1000*60*2