gpt4 book ai didi

java - Android AlarmManager.cancel() 实际上并没有取消闹钟/PendingIntent

转载 作者:行者123 更新时间:2023-12-01 14:13:05 38 4
gpt4 key购买 nike

尝试取消 AlarmManager 警报,但不太有效。

我像这样创建一个 PendingIntent:

static PendingIntent makePendingIntent(int id, Bundle bundle)
{
Intent intent = new Intent(mContext.getApplicationContext(), mfLocalNotificationManager.class);
if(bundle != null)
{
intent.putExtra(BUNDLE_ID, bundle);
}

return PendingIntent.getBroadcast(mContext.getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

}

从 SendLocalNotification 调用:

public static int SendLocalNotification(String title, String text, String tickerText, 
int timeSent, int timeOffset, String sound)
{

AlarmManager alarmMgr =
(AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);

Bundle notificationData = new Bundle();
notificationData.putString("title", title);
notificationData.putString("text", text);
notificationData.putString("tickerText", tickerText);
/*snip, bundle stuff*/

int noteID = title.hashCode();

notificationData.putInt("noteID", noteID);

PendingIntent pendingIntent = makePendingIntent(noteID, notificationData);

if( pendingIntent == null )
{
//This should probably be flagged as an error or an assertion.
Log.d("[MF_LOG]", "Java intent is null");
return -1;
}

//This isn't my timing code, don't hate me for it
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, timeOffset);

alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
pendingIntent);

return noteID;
}

并尝试像这样取消它(传递我们之前从 SendLocalNotification 返回的 id):

public static void CancelNotification(int id)
{
String ns = Context.NOTIFICATION_SERVICE;

AlarmManager alarmMgr =
(AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);

PendingIntent pendingIntent = makePendingIntent(id, null);

//This doesn't work...
pendingIntent.cancel(); //<- added based on SO post, doesn't help
alarmMgr.cancel(pendingIntent);
}

似乎什么都不起作用,我已经遵循了我能找到的其他帖子上的尽可能多的建议(确保 ID 相同,确保重新创建的 PendingIntent 完全相同),但它似乎仍然崩溃。附带说明一下,尝试使用标志 PendingIntent.FLAG_NO_CREATE 检查通知是否存在也不起作用,而是创建一个新对象而不是返回 null。

我正在测试的设备是 Nexus 7,我正在针对 API 9 进行构建。

最佳答案

您需要重新创建您的 Intent 并像这样取消它:

AlarmManager alarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
PendingIntent peding = PendingIntent.getActivity(context, code, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
alarm.cancel(peding);

关于java - Android AlarmManager.cancel() 实际上并没有取消闹钟/PendingIntent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18343708/

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