存储 ArrayList<PendingIntent>进入共享首选项 [英] Store ArrayList<PendingIntent> into SharedPreferences
问题描述
我找不到问题的答案,所以我决定发布一个问题.问题很简单.
II couldn't find an answer for my problem so I decided to post a question. The question is simple.
如何将 ArrayList
存储到 SharedPreferences
中?最好的方法是什么,我必须使用某种 Serialization
吗?
How can I store an ArrayList<PendingIntent>
into SharedPreferences
? What is the best way, do i have to use some kind of Serialization
?
预先感谢您,任何建议都会很棒!
Thank you in advance, any advice would be great!
推荐答案
PendingIntent
实现 Parcelable
.您需要遍历 ArrayList
并将每个 PendingIntent
转换为 String
.然后,您可以将所有单独的 String
连接成一个 String
(每个之间有一些分隔符).然后将生成的 String
写入 SharedPreferences
.
PendingIntent
implements Parcelable
. You'll need to loop through your ArrayList
and convert each PendingIntent
into a String
. You can then concatenate all the individual String
s into a single String
(with some delimiter in between each one). Then write the resulting String
to SharedPreferences
.
您可以像这样将 Parcelable
转换为 byte[]
:
You can convert a Parcelable
into a byte[]
like this:
PendingIntent pendingIntent = // Your PendingIntent here
Parcel parcel = Parcel.obtain(); // Get a Parcel from the pool
pendingIntent.writeToParcel(parcel, 0);
byte[] bytes = parcel.marshall();
parcel.recycle(); // Return the Parcel to the pool
现在使用 base64 编码(或任何其他机制,例如将每个字节转换为 2 个十六进制数字)将 byte[]
转换为 String
.要使用 base64,您可以这样做:
Now convert the byte[]
to a String
by using base64 encoding (or any other mechanism, like converting each byte into 2 hexadecimal digits). To use base64 you can do this:
String base64String = Base64.encodeToString(bytes, Base64.NO_WRAP | Base64.NO_PADDING);
见 如何在 Parcel 的帮助下将 Parcelable 编组和解组为字节数组? 有关如何将 Parcelable
转换为 byte[]
的更多信息和反之亦然.
See How to marshall and unmarshall a Parcelable to a byte array with help of Parcel? for more information about how to convert a Parcelable
to byte[]
and vice-versa.
这篇关于存储 ArrayList<PendingIntent>进入共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!