gpt4 book ai didi

java - Android - 在通知显示之前删除或取消通知

转载 作者:行者123 更新时间:2023-12-01 09:30:51 24 4
gpt4 key购买 nike

假设使用 AlarmManager 的通知是在特定日期设置的。如果我想在通知出现之前按下按钮来删除该通知,该怎么办?如果我没有记错的话, NotificationManager.cancel(id) 方法将取消当前显示的通知。如果我想在它出现之前将其删除怎么办?就像如何删除数组列表中的项目或如何删除数据库中的行一样。

<小时/>

示例,我有一个带有 id,namePerson 对象,每次我将 Person 添加到数据库时,都会发出一个 通知 将在指定日期设置。

下面是使用指定日期的日历实例和人员对象调用的设置通知方法:

 public void setNotification(Calendar calendar,Person person){
AlarmManager alertManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent();
intent.setAction("android.media.action.DISPLAY_NOTIFICATION");
intent.addCategory("android.intent.category.DEFAULT");
intent.putExtra("myTag",person);

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, person.getId(), intent, PendingIntent.FLAG_ONE_SHOT);
alertManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}

我的警报接收器类(是的,我正在实现 DAO 设计模式。我有一个 PersonDao 和 PersonDaoImpl,后者是一个单例类):

public class AlarmReceiver extends BroadcastReceiver {
final static String GROUP_KEY = "GROUP_KEY";

@Override
public void onReceive(Context context, Intent intent) {
//retrieve info:
PersonDAO personDao = PersonDAOImpl.getInstance(context);
Person person = (Person)intent.getSerializableExtra("myTag");
String name = person.getName();
long[] vibrationPattern = {0, 300, 0, 300};

Intent notificationIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(ViewDetails.class);
stackBuilder.addNextIntent(notificationIntent);

int requestCode = person.getId();
PendingIntent pendingIntent = stackBuilder.getPendingIntent(requestCode, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Deadline due today")
.setContentText("name: " + name)
.setTicker(name+"'s debt is due today")
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(Notification.PRIORITY_MAX)

.setContentIntent(pi)
.build();

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(requestCode, notification);


}

例如,警报接收器上设置的日期为 2016 年 9 月 12 日下午 3:00。当前日期是 2016 年 9 月 10 日。我想要做的是,当我删除数据库中的人员时,通知也会被删除/取消,因此在 2016 年 9 月 12 日下午 3:00 将不再有是一个警报通知。

最佳答案

如果您想取消通过 AlarmManager 安排的某些操作,请在 AlarmManager 上调用 cancel(),并传入等效的 PendingIntent 到您最初用来安排工作的那个。在这里,“等效 PendingIntent”,我的意思是:

  • 相同的操作(例如,getActivity()getService()getBroadcast())
  • 相同的请求代码(这些方法的第二个参数)
  • 等效的 Intent

通过“等效 Intent ”,我的意思是:

  • 相同的组件
  • 相同的 Action
  • 相同的 MIME 类型
  • 相同类别
  • 相同的数据 (Uri)

对于您在原始 PendingIntent 的原始 Intent 上设置的任何属性。

关于java - Android - 在通知显示之前删除或取消通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39416170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com