注意:本文的示例,用的是Kotlin,代碼邏輯模型是MVVM
Parcelable 與 Serializable,是數(shù)據(jù)序列化的2種方式,他們的區(qū)別有2個:
其一,Parcelable性能上優(yōu)于Serializable。Serializable是通過IO,存儲在硬盤上;而Parcelable則讀寫在內(nèi)存里面,速度上是大大優(yōu)于硬盤的。而且Serializable在實(shí)現(xiàn)的過程中,會用到反射技術(shù),產(chǎn)生大量的臨時對象。
其二,Serializable比Parcelable 代碼少,使用起來更簡單。
實(shí)際場景里面,只能2選1,盡管Serializable更簡單,但是為了app性能,最好還是用Parcelable。
剛開始做Android開發(fā)的時候,由于領(lǐng)路人用的是Serializable,所以就一直用,直到很久以后,才開始自己接觸Parcelable,下面分別示例怎么使用這2個對象
一、Serializable
繼承自Serializable的OneMoblie類
import java.io.Serializable
/**
* Created by Athrun on 2018/4/23.
*/
class OneMobile:Serializable {
var width:Int=1
var height:Int=1
var desity:Float=1f
}
執(zhí)行跳轉(zhuǎn)的 ViewModel
package com.viewmodel
import android.content.Context
import android.content.Intent
import android.util.Log
/**
* Created by Athrun on 2018/4/20.
*/
class VmParcelableActivity(var c:Context,var u:Util):BaseViewModel<ParcelableActivity>(c,u) {
override fun taskFinish() {
ACTIVITY?.finish()
}
init {
}
override fun onCreate() {
Thread(Runnable {
var p= mUtil?.api?.parcelableActivity()
}).start()
}
/** 跳轉(zhuǎn),數(shù)據(jù)傳遞**/
fun toIpcActivity(){
var mobile1=OneMobile()
mobile1.width=100;
mobile1.height=101;
mobile1.desity=102f;
var intentParams= Intent()
intentParams?.putExtra("seri",mobile1)
intentParams?.setClass(ACTIVITY,IpcActivity().javaClass)
ACTIVITY!!.startActivity(intentParams)
}
}
上面的 toIpcActivity() 這個fun就是跳轉(zhuǎn)的 數(shù)據(jù)傳遞寫法
目標(biāo)Activity
/**
* Created by Athrun on 2018/4/18.
*/
class IpcActivity :BaseActivity<IpcActivity, IpcLayoutBinding, VmIpcActivity>() {
/**承接Intent,跳轉(zhuǎn)數(shù)據(jù)**/
override fun getIntentData() {
var mobile1: OneMobile? = null
try {
mobile1 = intent.getSerializableExtra("seri") as OneMobile?
Util.log("result9"," mobile.wid="+mobile1?.width)
Util.log("result9"," mobile.hei="+mobile1?.height)
Util.log("result9"," mobile.dens="+mobile1?.desity)
} catch (e: Exception) {
}
}
override fun getContentView(): Int {
return R.layout.ipc_layout
}
override fun getViewModel(): VmIpcActivity {
return VmIpcActivity(context,mUtil!!)
}
override fun presenterTask() {
}
override fun update(o: Observable?, arg: Any?) {
}
}
最后的log
result9: mobile.wid=100
result9: mobile.hei=101
result9: mobile.dens=102.0
一句話,在觸發(fā)Activity執(zhí)行OneMobile封裝,在目標(biāo)Activity 進(jìn)行OneMobile解析。
Serializable 就寫完了,非常簡單。
二、Parcelable
明天跟新關(guān)于Parcelable的內(nèi)容