我想序列化一个Bundle对象,但似乎找不到一种简单的方法.使用Parcel似乎不是一个选项,因为我想将序列化数据存储到文件中.
有关如何做到这一点的任何想法?
我想要这个的原因是保存和恢复我的活动状态,当它被用户杀死时.我已经创建了一个Bundle,其中包含我要保存在onSaveInstanceState中的状态.但是当活动被SYSTEM杀死时,android只保留这个Bundle.当用户杀死活动时,我需要自己存储它.因此,我想将其序列化并存储到文件中.当然,如果你有任何其他方式来完成同样的事情,我也会感激.
编辑:我决定将我的状态编码为JSONObject而不是Bundle.然后可以将JSON对象作为Serializable放入Bundle中,或者存储到文件中.可能不是最有效的方式,但它很简单,似乎工作正常.
我正在尝试将一组StatusBarNotifications发送给我的另一个服务,所以我这样做了:
扩展的服务NotificationListenerService:
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
// TODO Auto-generated method stub
StatusBarNotification[] activeN = super.getActiveNotifications();
Intent i = new Intent(this, CoreTwo.class);
i.putExtra("activenotifications", activeN);
startService(i);
}
Run Code Online (Sandbox Code Playgroud)
但我得到一个关于文件描述符的RuntimeException.
我只找到几个环节解决这一问题,例如这一个在这里.答案提到了以下内容:
使用Bundle.putBinder()传递一个Binder,它将使用ParcelFileDescriptor(来自API 18)返回一个Parcel.但我不明白如何实现这一点.
此链接中的另一个人在这里提到以下内容:
如果我从ContentProvider返回PaecelFileDescriptor,它可以正常工作.
但我不明白他的意思.
最后一个环节是这个位置.它解决了与我相同的问题,但似乎没有解决方案.
有人理解我链接的这些潜在解决方案吗?是否有针对此问题的解决方法,可能是另一种发送数据的方式(StatusBarNotification [](它扩展了Parcelable))?
这是日志:
08-23 16:49:36.839: W/NotificationListenerService[NoLiSe](12804): Error running onNotificationPosted
08-23 16:49:36.839: W/NotificationListenerService[NoLiSe](12804): java.lang.RuntimeException: Not allowed to write file descriptors here
08-23 16:49:36.839: W/NotificationListenerService[NoLiSe](12804): at android.os.Parcel.nativeAppendFrom(Native Method)
08-23 16:49:36.839: W/NotificationListenerService[NoLiSe](12804): at android.os.Parcel.appendFrom(Parcel.java:431)
08-23 16:49:36.839: W/NotificationListenerService[NoLiSe](12804): at android.os.Bundle.writeToParcel(Bundle.java:1679)
08-23 …Run Code Online (Sandbox Code Playgroud) 我正在编写一个 Android 应用程序,其中我的服务需要将图像发送到其他一些应用程序(通过广播消息或启动服务 - 有多个应用程序可能有兴趣接收图像)。
如果我将图像加载到位图对象中并将其作为意图的“额外”,它实际上会起作用。但是,我想看看是否可以发送一个 ParcelFileDescriptor,并让客户端自行加载 Bitmap 对象(从阅读规范来看,ParcelFileDescriptor 似乎就是为了这个目的而创建的 - 在进程之间共享文件)。这里我试图避免通过 Intent 发送大对象。所以我写了这样的东西:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("Service is called" + this.getClass());
Intent newIntent = new Intent(MY_ACTION);
try {
File icon = new File(getExternalFilesDir(null), "robot_icon.jpg");
icon.setReadable(true, false);
if( !icon.exists() ) {
System.out.println("Writting file " + icon);
FileOutputStream out;
out = new FileOutputStream(icon);
BitmapFactory.decodeResource(getResources(), R.drawable.two_face_answer_map).compress(CompressFormat.JPEG, 100, out);
out.close();
System.out.println("Closing file after writing" + icon);
}
newIntent.putExtra(EXTRA_BITMAP, ParcelFileDescriptor.open(icon, ParcelFileDescriptor.MODE_READ_WRITE));
// sendBroadcast(newIntent);
startService(newIntent);
} catch (FileNotFoundException …Run Code Online (Sandbox Code Playgroud)