我正在开发一个应用程序,我想在其中将待定 Intent 保存到共享首选项中,并在共享首选项中存在该待定 Intent 时对应用程序执行一些操作。
引用链接:
Store ArrayList<PendingIntent> into SharedPreferences
但在此链接中也没有找到解决方案。
如果有人知道我该怎么做,请告诉我。
谢谢。
最佳答案
您在评论中写道:
If you have multiple alarms and you want to cancel a few of them, then I think we can cancel only through its
PendingIntent
. That is the reason why I am savingPendingIntent
. Is my approach right for this?
没有。这不是解决此问题的正确方法。
是的,您需要向 AlarmManager.cancel()
提供一个 PendingIntent
。但是,您不需要将 PendingIntent
保存在持久存储中。您需要做的是在持久存储中保存足够的信息,以便您可以重新创建 PendingIntent
。
要重新创建 PendingIntent
,您只需执行以下操作:
Intent intent = new Intent(context, MyActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.NO_CREATE);
if (pendingIntent != null) {
alarmManager.cancel(pendingIntent); // cancel alarm
pendingIntent.cancel(); // delete the PendingIntent
}
我在示例代码中使用了 Activity
,但您也可以使用 Service
或 BroadcastReceiver
,无论您在你的代码。
如果您只想使用它来取消现有警报,则不需要向Intent
添加任何额外内容。
如果您有多个警报,Intent
必须是唯一的。您只需要保存您正在使用的任何内容以使其唯一(requestCode
或 Intent
ACTION 或其他),然后使用相同的参数重新创建 PendingIntent
当你想取消闹钟时。
关于android - 以数组列表或其他形式将待定 Intent 保存到共享首选项中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49570289/