Search code examples
androidarraylistsharedpreferencesandroid-pendingintent

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


i am working on an App in which i want to save the pending intent into shared preference and perform some action on app if that pending intent exist in shared preferences.

Reference Link :

Store ArrayList<PendingIntent> into SharedPreferences

but no solution found in this link as well.

if someone know how can i do this then plz let me know.

Thanks.


Solution

  • You wrote in a comment:

    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?

    No. This isn't the right approach to solve this problem.

    Yes, you'll need to provide a PendingIntent to AlarmManager.cancel(). However, you don't need to save the PendingIntent in a persistent store. What you need to do is to save enough information in the persistent store so that you can recreate the PendingIntent.

    To recreate the PendingIntent you just do this:

    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
    }
    

    I've used an Activity in the example code, but you can also use a Service or BroadcastReceiver, whatever you are using in your code.

    You do NOT need to add any extras to the Intent if you just want to use it to cancel an existing alarm.

    If you have multiple alarms, the Intents must be unique. You just need to save whatever you are using to make them unique (requestCode, or Intent ACTION, or whatever) and then use the same parameters to recreate the PendingIntent when you want to cancel the alarms.