android - 以数组列表或其他形式将待定 Intent 保存到共享首选项中?

标签 android arraylist sharedpreferences android-pendingintent

我正在开发一个应用程序,我想在其中将待定 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 saving PendingIntent. 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,但您也可以使用 ServiceBroadcastReceiver,无论您在你的代码。

如果您只想使用它来取消现有警报,则不需要Intent 添加任何额外内容。

如果您有多个警报,Intent必须是唯一的。您只需要保存您正在使用的任何内容以使其唯一(requestCodeIntent ACTION 或其他),然后使用相同的参数重新创建 PendingIntent 当你想取消闹钟时。

关于android - 以数组列表或其他形式将待定 Intent 保存到共享首选项中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49570289/

相关文章:

android - 在 Google Maps V2 中将相机居中

android - 我没有名为 values v21 的单独文件夹

java - 循环遍历具有相同属性 (catalog_id) 的项目出现情况

java - 清除数据后从共享偏好中获取值(value)

c# - 尝试将经度和纬度转换为地址名称,但它跳过了太多帧

android - 如何提示用户在 Android 锁屏中输入密码?

java - 如果对同一个集合调用同一个迭代器两次,会发生什么情况?

Java:制作初始 ArrayList 的本地副本的最快方法?

android - 如何使用共享首选项

android - BroadcastReceiver 中的 SharedPreferences 似乎没有更新?