且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

存储 ArrayList进入共享首选项

更新时间:2023-02-02 21:05:41

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 Strings 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.