1、Parcelable和Serializable的異同
我們知道在Java應(yīng)用程序當(dāng)中對類進行序列化操作只需要實現(xiàn)Serializable接口就可以畦徘,由系統(tǒng)來完成序列化和反序列化操作崇摄。但是在Android中序列化操作有另外一種方式來完成果正,那就是實現(xiàn)Parcelable接口养筒。Parcelable的性能要強于Serializable试躏,因此在絕大多數(shù)的情況下帜消,Android還是推薦使用Parcelable來完成對類的序列化操作的棠枉。
Parcelable和Serializable的性能對比如下所述:
后者在序列化操作的時候會產(chǎn)生大量的臨時變量,(原因是使用了反射機制)從而導(dǎo)致GC的頻繁調(diào)用泡挺,因此在性能上會稍微遜色辈讶。
Parcelable是以Ibinder作為信息載體的,在內(nèi)存上的開銷比較小娄猫,因此在內(nèi)存之間進行數(shù)據(jù)傳遞的時Android推薦使用Parcelable贱除。
在讀寫數(shù)據(jù)的時候,Parcelable是在內(nèi)存中直接進行讀寫媳溺,而Serializable是通過使用IO流的形式將數(shù)據(jù)讀寫入在硬盤上月幌。
2、淺析Parcel源碼
public final class Parcel {
// 保存的是 c++ 層的 Parcel.cpp 對象的指針地址
private long mNativePtr; // used by native code
private Parcel(long nativePtr) {
if (DEBUG_RECYCLE) {
mStack = new RuntimeException();
}
init(nativePtr);
}
private void init(long nativePtr) {
if (nativePtr != 0) {
mNativePtr = nativePtr;
mOwnsNativeParcelObject = false;
} else {
mNativePtr = nativeCreate();
mOwnsNativeParcelObject = true;
}
}
/**
* Write an integer value into the parcel at the current dataPosition(),
* growing dataCapacity() if needed.
*/
public final void writeInt(int val) {
nativeWriteInt(mNativePtr, val);
}
/**
* Read an integer value from the parcel at the current dataPosition().
*/
public final int readInt() {
return nativeReadInt(mNativePtr);
}
// 創(chuàng)建 Parcel.cpp 返回 jlong
private static native long nativeCreate();
// 寫入 int 數(shù)據(jù)
private static native void nativeWriteInt(long nativePtr, int val);
// 讀 int 數(shù)據(jù)
private static native int nativeReadInt(long nativePtr);
}
// 創(chuàng)建 Parcel 褂删,返回指針地址給 java 層
static jlong android_os_Parcel_create(JNIEnv* env, jclass clazz)
{
Parcel* parcel = new Parcel();
return reinterpret_cast<jlong>(parcel);
}
// 通過指針地址獲取 c++ 層的對象飞醉,然后進行操作
static void android_os_Parcel_writeInt(JNIEnv* env, jclass clazz, jlong nativePtr, jint val) {
Parcel* parcel = reinterpret_cast<Parcel*>(nativePtr);
if (parcel != NULL) {
const status_t err = parcel->writeInt32(val);
if (err != NO_ERROR) {
signalExceptionForError(env, clazz, err);
}
}
}
status_t Parcel::writeInt32(int32_t val)
{
return writeAligned(val);
}
template<class T>
status_t Parcel::writeAligned(T val) {
COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
// 判斷大小有沒有超過
if ((mDataPos+sizeof(val)) <= mDataCapacity) {
restart_write:
// 往內(nèi)存上寫入數(shù)據(jù)
*reinterpret_cast<T*>(mData+mDataPos) = val;
// 返回寫入成功
return finishWrite(sizeof(val));
}
// 返回錯誤
status_t err = growData(sizeof(val));
if (err == NO_ERROR) goto restart_write;
return err;
}
int32_t Parcel::readInt32() const
{
return readAligned<int32_t>();
}
template<class T>
T Parcel::readAligned() const {
T result;
if (readAligned(&result) != NO_ERROR) {
result = 0;
}
return result;
}
template<class T>
status_t Parcel::readAligned(T *pArg) const {
COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
// 有沒有超出
if ((mDataPos+sizeof(T)) <= mDataSize) {
// 去除當(dāng)前內(nèi)存上的值
const void* data = mData+mDataPos;
// 當(dāng)前累加往后邏動
mDataPos += sizeof(T);
// 取出來并賦值
*pArg = *reinterpret_cast<const T*>(data);
return NO_ERROR;
} else {
return NOT_ENOUGH_DATA;
}
}
Parcel 其實就是在 native 層開辟了一塊內(nèi)存,然后按照一定的順序往這塊內(nèi)存里面寫數(shù)據(jù)屯阀。當(dāng)我需要取數(shù)據(jù)的時候缅帘,我們按照原來寫的順序取出來就可以了。寫的順序和取的順序必須保持一致难衰,不然肯定會出錯钦无。
接下來手動簡單實現(xiàn)一下,既能學(xué)習(xí)JNI的知識又能加深印象盖袭。
3失暂、實踐
現(xiàn)在我們新建一個Parcel類,里面有四個native方法彼宠。
// 找到Parcel.class,使用“javap -s Parcel”查看方法簽名
public class Parcel {
private static long mNativePtr = 0;
static {
System.loadLibrary("ndksample");
mNativePtr = nativeCreate();
}
void writeInt(int value) {
nativeWriteInt(mNativePtr, value);
}
int readInt() {
return nativeReadInt(mNativePtr);
}
void setDataPosition(int pos) {
nativeSetDataPosition(mNativePtr, pos);
}
static native long nativeCreate();
native void nativeWriteInt(long nativePtr, int value);
native int nativeReadInt(long nativePtr);
native void nativeSetDataPosition(long nativePtr, int pos);
}
接下來寫JNI部分,首先是Parcel.h弟塞。
#ifndef NDKSAMPLE_PARCEL_H
#define NDKSAMPLE_PARCEL_H
#include <malloc.h>
#include <stdio.h>
class Parcel {
private:
char *mData;
int mDataPos;
public:
Parcel() {
mData = (char *) malloc(1024);
mDataPos = 0;
}
~ Parcel() {
free(mData);
}
void writeInt(int value) {
*reinterpret_cast<int *>(mData + mDataPos) = value;
mDataPos += sizeof(value);
}
int readInt() {
int result = *reinterpret_cast<int *>(mData + mDataPos);
mDataPos += sizeof(int);
return result;
}
void setDataPosition(int pos) {
mDataPos = pos;
}
};
#endif //NDKSAMPLE_PARCEL_H
最后是寫Native-lib.cpp代碼:
#include <jni.h>
#include <string>
#include <android/log.h>
#include "Parcel.h"
#define TAG "@@"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__)
jlong jni_nativeCreate(JNIEnv *env, jobject jobject1) {
Parcel *parcel = new Parcel();
return reinterpret_cast<jlong>(parcel);
}
void jni_nativeWriteInt(JNIEnv *env, jobject jobject1,jlong nativePtr, jint value) {
Parcel *parcel = reinterpret_cast<Parcel *>(nativePtr);
parcel->writeInt(value);
}
jint jni_nativeReadInt(JNIEnv *env, jobject jobject1,jlong nativePtr) {
Parcel *parcel = reinterpret_cast<Parcel *>(nativePtr);
return parcel->readInt();
}
void jni_nativeSetDataPosition(JNIEnv *env, jobject jobject1,jlong nativePtr, jint pos) {
Parcel *parcel = reinterpret_cast<Parcel *>(nativePtr);
parcel->setDataPosition(pos);
}
// 第一個參數(shù)a 是java native方法名凭峡,
// 第二個參數(shù) 是native方法參數(shù),括號里面是傳入?yún)⒌念愋停膺叺氖欠祷刂殿愋停?// 第三個參數(shù) 是c/c++方法名决记。
static const JNINativeMethod nativeMethod[] = {
{"nativeCreate", "()J", (void *) jni_nativeCreate},
{"nativeWriteInt", "(JI)V", (void *) jni_nativeWriteInt},
{"nativeReadInt", "(J)I", (void *) jni_nativeReadInt},
{"nativeSetDataPosition", "(JI)V", (void *) jni_nativeSetDataPosition}
};
static int registNativeMethod(JNIEnv *env) {
int result = -1;
jclass class_text = env->FindClass("com.dawn.ndksample.Parcel");
if (env->RegisterNatives(class_text, nativeMethod,
sizeof(nativeMethod) / sizeof(nativeMethod[0])) == JNI_OK) {
result = 0;
}
return result;
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env = NULL;
int result = -1;
if (vm->GetEnv((void **) &env, JNI_VERSION_1_1) == JNI_OK) {
if (registNativeMethod(env) == JNI_OK) {
result = JNI_VERSION_1_6;
}
return result;
}
}
驗證:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parcel parcel = new Parcel();
parcel.writeInt(123);
parcel.writeInt(456);
parcel.setDataPosition(0);
int result = parcel.readInt();
int result2 = parcel.readInt();
Log.d("@@","result:"+result+",result2:"+result2);
}
// 輸出結(jié)果 >>> result:123,result2:456
}
P.S. 上面的cpp代碼使用了動態(tài)注冊的寫法摧冀,如有不了解的請先自行百度,我將在下次補充系宫。
撒花索昂,謝謝大家的閱讀。