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

Saving Pending-Intent into Shared Preferences in form of Array-list or anything?

我正在开发一个应用程序,我想在其中将待定意图保存到共享首选项中,并在共享首选项中存在该待定意图时对应用程序执行一些操作。

参考Link:

Store ArrayList<PendingIntent> into SharedPreferences

但在此 link 中也未找到解决方案。

如果有人知道我该怎么做,请告诉我。

谢谢。

您在评论中写道:

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?

没有。这不是解决这个问题的正确方法。

是的,您需要提供一个 PendingIntentAlarmManager.cancel()。但是,您不需要将 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添加任何额外功能,如果您只想使用它来取消现有闹钟。

如果您有多个警报,Intents 必须是唯一的。你只需要保存你正在使用的任何东西来使它们独一无二(requestCode,或 Intent ACTION,或其他),然后在你想取消时使用相同的参数重新创建 PendingIntent闹钟。