gpt4 book ai didi

android - 使用 cancel 取消 AlarmManager 事件

转载 作者:行者123 更新时间:2023-11-29 01:46:39 25 4
gpt4 key购买 nike

PendingIntent cancel() API 文档说:

Cancel a currently active PendingIntent. Only the original application owning a PendingIntent can cancel it.

我不太清楚这句话的意思。如果我像这样从 Activity x 设置 AlarmManager 事件:

PendingIntent pendingIntent;
Intent myIntent = new Intent(x.this, AlarmReciever.class);

myIntent.putExtra("task_uuid", task_uuid);
pendingIntent = PendingIntent.getBroadcast(x.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, dateTime.getTimeInMillis(), pendingIntent);

我的问题是:我可以使用以下方法取消 y Activity 中的未决 Intent 吗:

PendingIntent pendingIntent;
Intent myIntent = new Intent(y.this, AlarmReciever.class);

myIntent.putExtra("task_uuid", task_uuid);
pendingIntent = PendingIntent.getBroadcast(y.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);

最佳答案

当你设置闹钟时需要在PendingIntent中传递一个键值,它会区分是否有闹钟,应该是这样的

pendingIntent = PendingIntent.getBroadcast(x.this, key_value, myIntent,0);
SharedPreferences settings = context.getSharedPreferences("alarm", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, false);
editor.commit();

要取消相同的警报,您需要将 key_values 保存在某个位置,您可以使用共享首选项。得到相同的 key 然后像这样取消警报

SharedPreferences settings = context.getSharedPreferences("alarm", 0);             
Map<String,?> allNotifyIdsMap = settings.getAll();
if(allNotifyIdsMap!=null&&allNotifyIdsMap.isEmpty()==false)
{
for(String notifyId: allNotifyIdsMap.keySet())
{
boolean isCleared = settings.getBoolean(notifyId, false);
if(isCleared==false)
{
pendingIntent = PendingIntent.getBroadcast(y.this, key_value, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
}

关于android - 使用 cancel 取消 AlarmManager 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21044441/

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