存储ArrayList< PendingIntent>进入SharedPreferences [英] Store ArrayList<PendingIntent> into SharedPreferences
问题描述
II无法找到我的问题的答案,所以我决定发布一个问题.问题很简单.
II couldn't find an answer for my problem so I decided to post a question. The question is simple.
如何将ArrayList<PendingIntent>
存储到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);
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>进入SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!