为什么Android为序列化对象提供了两个接口?序列化对象与Android Binder和AIDL文件interopt ?


当前回答

我的回答有点晚了,但我希望它能帮助到其他人。

在速度方面,可打包>序列化。但是,自定义Serializable是个例外。它几乎在Parcelable的范围内,甚至更快。

参考资料:https://www.geeksforgeeks.org/customized-serialization-and-deserialization-in-java/

例子:

要序列化的自定义类

class MySerialized implements Serializable { 

    String deviceAddress = "MyAndroid-04"; 

    transient String token = "AABCDS"; // sensitive information which I do not want to serialize

    private void writeObject(ObjectOutputStream oos) throws Exception {
        oos.defaultWriteObject();
        oos.writeObject("111111" + token); // Encrypted token to be serialized
    }

    private void readObject(ObjectInputStream ois) throws Exception {
        ois.defaultReadObject(); 
        token = ((String) ois.readObject()).subString(6);  // Decrypting token
    }

}

其他回答

1. 可序列化的

@see http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

什么接口?

是标准的Java接口吗

速度

比Parcelable慢

2. Parcelable

@see http://developer.android.com/reference/android/os/Parcelable.html

什么接口?

android。操作系统接口 这意味着谷歌开发的Parcelable在android上有更好的性能

速度

更快(因为它针对android开发进行了优化)

综上所述

要知道Serializable是一个标准的Java接口,Parcelable是Android开发的接口

If you want to be a good citizen, take the extra time to implement Parcelable since it will perform 10 times faster and use less resources. However, in most cases, the slowness of Serializable won’t be noticeable. Feel free to use it but remember that serialization is an expensive operation so keep it to a minimum. If you are trying to pass a list with thousands of serialized objects, it is possible that the whole process will take more than a second. It can make transitions or rotation from portrait to lanscape feel very sluggish.

来源:http://www.developerphil.com/parcelable-vs-serializable/

你可以在intent中使用serializable对象,但是在使serialize成为Parcelable对象的时候,它会给出一个严重的异常,比如NotSerializableException。不建议使用serializable和Parcelable。所以最好是扩展Parcelable与你想要使用的对象捆绑和意图。由于这个Parcelable是android特定的,所以它没有任何副作用。 :)

1. 可序列化的

接口是一个标记(没有抽象方法的接口),不需要重新定义任何东西。

2. Parcelable

具有抽象方法的接口。在实现它的时候,你需要重新定义所有的抽象方法,指定哪些字段以及你需要写/读的顺序(通常工作室自己可以生成它们)。

实际上没有人用Kotlin编写。对此有一个特殊的注释,由于它,这个接口的实现将自动生成。要使用它,你需要添加一个特殊的插件。

在构建。Gradle插件部分,添加另一个插件:id 'kotlin-parcelize'

同步项目

您不必担心实现方法,您所需要的只是实现Parcelable接口并添加@Parcelize注释。

一切都会好的,工作很快!

结果

如果实现Parcelable接口而不是Serializable接口,实现过程会更快。

Parcelable将对象转换为字节流,以便在Android的进程之间传递对象。

序列化将POJO转换为字符串(JSON字符串),并用于跨平台传输对象信息。