[Android] Serialization principle Parcelable

 Parcelable is a serialization interface provided by Android. The use of Parcelable is more complicated than Serializable, but the efficiency of Parcelable is much higher than that of Serializable. This has always been the pride of Google engineers. The efficiency of Parcelable and Serializable is compared with Parcelable. vs Serializable claims to be 10 times faster in efficiency

Parcelable is provided by the Android SDK. It is based on memory. Since the read and write speed of memory is higher than that of the hard disk, the transfer of cross-process objects in Android generally uses Parcelable

Parcelable implements generators


kotlin-parcelize The plugin provides a  Parcelable  implementation generator, add the following Gradle plugin to your application's  build.gradle files:

plugins {
    id("kotlin-parcelize")
}

When using  @Parcelize to add annotations to a class, the system will automatically generate an  Parcelable的 implementation, as shown below:

import kotlinx.parcelize.Parcelize

@Parcelize
class User(val firstName: String, val lastName: String, val age: Int): Parcelable

要注意的是:@Parcelize Requires that all serialization properties be declared in the primary constructor.

 If your class requires more advanced serialization logic, write it in some companion class:

@Parcelize
data class User(val firstName: String, val lastName: String, val age: Int) : Parcelable {
    private companion object : Parceler<User> {
        override fun User.write(parcel: Parcel, flags: Int) {
            // Custom write implementation
        }

        override fun create(parcel: Parcel): User {
            // Custom read implementation
        }
    }
}

Source code analysis of Parcelable serialization process


 Parcelable interface

There is a writeToParcel method in the Parcelable interface

 Come to the Parcel class of the writeToParcel method. Compared with the courier's package, Parcel requires us to write data into Parcel, and then the recipient can get the data from the package.

 There are a series of native methods in Parcel. What do native methods do? The native method is to write our data type into it.

In general: Parcelable implements reading and writing through Parcel, thereby realizing serialization and deserialization

 Parcelable serialization basic method


 private fun test() {
        var parcel:Parcel=Parcel.obtain()
        parcel.writeInt(19)
        parcel.writeInt(12)
        //marshall方法转换成二进制
        val bs=parcel.marshall()
        Log.d("data","bs=${bs.size}")
        //把parcel释放掉
        parcel.setDataPosition(0)
        parcel.recycle()
        //重新获取一个parcel
        parcel=Parcel.obtain()
        //把bs字节流放到parcel里面去
        parcel.unmarshall(bs,0,bs.size)
        //把parcel里面的值读取出来
        val size=parcel.dataSize()
        for(i in 0..size step 4){
            parcel.setDataPosition(i)
            Log.d("data","value=${parcel.readInt()}")
        }
        parcel.recycle()
    }

 Pass objects between Parcelable processes


Create a Course class that implements the Parcelable interface

@Parcelize
class Course(var name:String, var score:Int) :Parcelable{
}

 Write the following code in an activity

       val course=Course("数学",99)
        var intent=Intent(this,MainActivity4::class.java)
        intent.putExtra("data",course)
        startActivity(intent)

Write the following code in another activity 

        var course=intent.getParcelableExtra<Course>("data")
        if (course != null) {
            Log.d("data","${course.name}---${course.score}")
        }

Result display 

 D/data: Mathematics---99

How to choose between Parcelable and Serializable


1. In terms of memory usage, Parcelable has higher performance than Serializable, so Parcelable is recommended.

2.Serializable will generate a large number of temporary variables during serialization, which will cause frequent GC.

3. Parcelable cannot be used in the case of storing data on a disk, because Parcelable cannot guarantee the continuity of data very well. In the case of external changes, it is recommended to use Serializable.

Guess you like

Origin blog.csdn.net/weixin_63357306/article/details/128574077