Parcelable和Serializable
我们在开发过程中会用到序列化,有java的Serializable,也有Android自带的Parcelable。我们也清楚Parcelable的设计初衷是因为Serializable效率过慢,为了在程序内不同组件间以及不同Android程序间(AIDL)高效的传输数据而设计。
效率及选择
Parcelable的性能比Serializable好,在内存开销方面较小,所以在内存间数据传输时推荐使用Parcelable,如activity间传输数据,而Serializable可将数据持久化方便 保存,所以在需要保存或网络传输数据时选择Serializable,因为android不同版本 Parcelable可能不同,所以不推荐使用Parcelable进行数据持久化
Parcelable为啥高效
Serializable 开销大,Parcelable更加高效,但是若要问为什么是这样?那么下面就带大家来了解这些知识。
我们在写一些bean的时候会去实现Parcelable接口,就会使用到Parcel对象的一些方法,如下Student的bean。
public class Student implements Parcelable {
public String name;
public int age;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeInt(this.age);
}
public void readFromParcel(Parcel source) {
this.name = source.readString();
this.age = source.readInt();
}
public Student() {
}
protected Student(Parcel in) {
this.name = in.readString();
this.age = in.readInt();
}
public static final Creator<Student> CREATOR = new Creator<Student>() {
@Override
public Student createFromParcel(Parcel source) {
return new Student(source);
}
@Override
public Student[] newArray(int size) {
return new Student[size];
}
};
}
接下来我们分析一些Parcel的源码
frameworks/base/core/java/android/os/Parcel.java
public final class Parcel {
// 保存的是 c++ 层的 Parcel.cpp 对象的指针地址
private long mNativePtr; // used by native code
private Parcel(long nativePtr) {
if (DEBUG_RECYCLE) {
mStack = new RuntimeException();
}
//Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
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);
}
// 创建 Parcel.cpp 返回 jlong
private static native long nativeCreate();
// 写入 int 数据
private static native void nativeWriteInt(long nativePtr, int val);
// 读 int 数据
private static native int nativeReadInt(long nativePtr);
}
frameworks/base/core/jni/android_os_Parcel.cpp
// 创建 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);
}
}
}
frameworks/native/libs/binder/Parcel.cpp
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:
// 往内存上写入数据
*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) {
// 去除当前内存上的值
const void* data = mData+mDataPos;
// 当前累加往后逻动
mDataPos += sizeof(T);
// 取出来并赋值
*pArg = *reinterpret_cast<const T*>(data);
return NO_ERROR;
} else {
return NOT_ENOUGH_DATA;
}
}
看到这里再来说共享内存,或者说 binder 驱动就会变得简单起来了,Parcel 其实就是在 native 层开辟了一块内存,然后按照一定的顺序往这块内存里面写数据。当我需要取数据的时候,我们按照原来写的顺序取出来就可以了。写的顺序和取的顺序必须保持一致,不然肯定会出错。那为什么不在 java 层做呢?请问在 java 层能做到这些效果吗?这也证实了其实 c 和 c++ 更加灵活,因为操作的是一块内存地址上的数据,想干嘛就可以干嘛。怎么回答上面的问题应该不用我说了,了解了原理那么在回答的时候可以自己做一些扩展。
Parcel数据结构
既然是 JNI 基础部分,那么我们最好还是自己动手来敲一下。
首先先分析一下Parcel的数据是怎么存储的。
Parcel数据结构图.png
如上图:首先存入的是两个int类型的数据23和100,然后在存入的是char类型的数据'Z',最后存入的是String类型的数据,这里重点说一下String是怎么存入的。
存入String类型的数据,首先先把String类型的数据的长度以int类型存入String类型的数据的开始位置,然后接下来在存入String字符串。具体存入String类型的数据的逻辑可以看下面的Parcel.cpp
里的writeString16
方法
手写Parcel
MainActivity.kt
var parcel = MyParcel()
parcel.writeInt(23)
parcel.writeInt(100)
parcel.writeChar('Z')
parcel.writeString("zhangSan")
parcel.writeInt(34)
Log.e("zuojie", "==write data over==" )
parcel.setDataPosition(0)
Log.e("zuojie", "==readInt111==" + parcel.readInt())
Log.e("zuojie", "==readInt222==" + parcel.readInt())
Log.e("zuojie", "==readChar==" + parcel.readChar())
Log.e("zuojie", "==readString==" + parcel.readString())
Log.e("zuojie", "==readInt333==" + parcel.readInt())
MyParcel.kt
class MyParcel {
private var mNativePtr: Long = 0
init {
System.loadLibrary("native-lib")
mNativePtr = nativeCreate();
}
fun writeInt(value: Int) {
nativeWriteInt(mNativePtr,value)
}
fun readInt() = nativeReadInt(mNativePtr)
fun setDataPosition(position : Int) = nativeSetDataPosition(mNativePtr,position)
/*fun setDataPosition(position : Int){
nativeSetDataPosition(mNativePtr,position)
}*/
fun writeChar(value:Char){
nativeWriteChar(mNativePtr,value)
}
fun readChar():Char{
return nativeReadChar(mNativePtr)
}
fun writeString(str:String){
nativeWriteString(mNativePtr,str)
}
fun readString():String{
return nativeReadString(mNativePtr);
}
private external fun nativeCreate(): Long
private external fun nativeWriteInt(mNativePtr: Long, value: Int)
private external fun nativeReadInt(mNativePtr: Long):Int
private external fun nativeWriteChar(mNativePtr: Long,value :Char)
private external fun nativeReadChar(mNativePtr:Long):Char
private external fun nativeSetDataPosition(mNativePtr: Long, position: Int)
private external fun nativeWriteString(mNativePtr: Long, str: String)
private external fun nativeReadString(mNativePtr: Long):String
}
native-lib.cpp
#include <jni.h>
#include <string>
#include "Parcel.h"
#include <android/log.h>
#define TAG "zuojie"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__);
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__);
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__);
extern "C"
JNIEXPORT jlong JNICALL
Java_com_zxj_parcel_MyParcel_nativeCreate(JNIEnv *env, jobject thiz) {
Parcel *parcel = new Parcel();
return reinterpret_cast<jlong>(parcel);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_zxj_parcel_MyParcel_nativeWriteInt(JNIEnv *env, jobject thiz, jlong m_native_ptr,
jint value) {
Parcel *parcel = reinterpret_cast<Parcel *>(m_native_ptr);
parcel->writeInt(value);
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_zxj_parcel_MyParcel_nativeReadInt(JNIEnv *env, jobject thiz, jlong m_native_ptr) {
Parcel *parcel = reinterpret_cast<Parcel *>(m_native_ptr);
int result = parcel->readInt();
return result;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_zxj_parcel_MyParcel_nativeSetDataPosition(JNIEnv *env, jobject thiz, jlong m_native_ptr,
jint position) {
Parcel *parcel = reinterpret_cast<Parcel *>(m_native_ptr);
LOGE("position = %d\n",position)
parcel->setDataPosition(position);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_zxj_parcel_MyParcel_nativeWriteString(JNIEnv *env, jobject thiz, jlong m_native_ptr,
jstring val) {
Parcel *parcel = reinterpret_cast<Parcel *>(m_native_ptr);
// const jchar * str = env->GetStringCritical(val, 0);
const char *str = env->GetStringUTFChars(val, 0);
int err = -1;
if (str) {
jsize length = env->GetStringLength(val);
LOGE("length= %d,str=%s",length,str)
err = parcel->writeString16(reinterpret_cast<const char16_t *>(str), length);
env->ReleaseStringUTFChars(val,str);
}
}
extern "C"
JNIEXPORT jstring JNICALL
Java_com_zxj_parcel_MyParcel_nativeReadString(JNIEnv *env, jobject thiz, jlong m_native_ptr) {
Parcel *parcel = reinterpret_cast<Parcel *>(m_native_ptr);
const char16_t *data = parcel->readString16Inplace();
jstring pJstring = env->NewStringUTF(reinterpret_cast<const char *>(data));
return pJstring;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_zxj_parcel_MyParcel_nativeWriteChar(JNIEnv *env, jobject thiz, jlong m_native_ptr,
jchar value) {
Parcel *parcel = reinterpret_cast<Parcel *>(m_native_ptr);
LOGE("value=%d",value);
parcel->writeChar(value);
}
extern "C"
JNIEXPORT jchar JNICALL
Java_com_zxj_parcel_MyParcel_nativeReadChar(JNIEnv *env, jobject thiz, jlong m_native_ptr) {
Parcel *parcel = reinterpret_cast<Parcel *>(m_native_ptr);
return parcel->readChar();
}
Parcel.cpp
#include <cstdlib>
#include "Parcel.h"
Parcel::Parcel() {
this->mData = static_cast<char *>(malloc(1024));
}
Parcel::~Parcel() {
LOGE("Parcel的析构函数调用了")
if(this->mData){
free(this->mData);
this->mData = NULL;
}
}
void Parcel::writeInt(int value) {
* reinterpret_cast<int *>(this->mData + this->mDataPos) = value;
mDataPos += sizeof(int);
}
int Parcel::readInt() {
int result = *reinterpret_cast<int *>(this->mData + this->mDataPos);
mDataPos += sizeof(int);
return result;
}
void Parcel::setDataPosition(int position) {
this->mDataPos = position;
}
void Parcel::writeChar(char value) {
LOGE("Parcel-> value= %d",value);
*(this->mData + this->mDataPos) = value;
mDataPos += sizeof(char);
}
char Parcel::readChar() {
char result = *(this->mData + this->mDataPos);
mDataPos += sizeof(char);
return result;
}
int Parcel::writeString16(const char16_t *str, int len) {
if (str == NULL) return -1;
writeInt32(len);
len *= sizeof(char16_t);
LOGE("[len *= sizeof(char16_t)] = %d",len)
uint8_t * data = writeInplace(len +sizeof(char16_t));
LOGE("mDataPos = %d,len=%d,str=%s",mDataPos,len,str)
if (data) {
memcpy(data, str, len);
LOGE("data=%s",data);
* reinterpret_cast<char16_t*>(data + len) = 0;//可以不要
return 0;
}
return -1;
}
const char16_t* Parcel::readString16Inplace() {
int32_t size = readInt32();
LOGE("readString16Inplace=>size=%d , [(size+1)*sizeof(char16_t )]=%d",size,(size+1)*sizeof(char16_t ))
const char16_t* str = (const char16_t*)readInplace((size+1)*sizeof(char16_t ));
return str;
}
int Parcel::writeInt32(int32_t len) {
//存字符串的长度值
* reinterpret_cast<int32_t *>(mData + mDataPos) = len;
LOGE("writeInt32=>mDataPos=%d, 把字符串的长度len=%d存储首位",mDataPos,* reinterpret_cast<int *>(mData + mDataPos));
return finisWrite(sizeof(len));
}
int Parcel::finisWrite(size_t len) {
mDataPos +=len;
LOGE("finisWrite=>sizeof(len)=%d,mDataPos=%d",len,mDataPos);
return 0;
}
uint8_t *Parcel::writeInplace(size_t len) {
uint8_t* data = reinterpret_cast<uint8_t *>(mData + mDataPos);
LOGE("writeInplace=>mDataPos=%d 获取[len*sizeof(char16_t) +sizeof(char16_t)]=%d的值%d",mDataPos,len ,*data);
finisWrite(len);
return data;
}
int32_t Parcel::readInt32() {
//取出字符串的长度值
const void* data = mData + mDataPos;
LOGE("start readInt32=>mDataPos=%d",mDataPos)
// mDataPos +=sizeof(int32_t);
finisWrite(sizeof(int32_t));
LOGE("end readInt32=>mDataPos=%d,data=%d",mDataPos,data)
int32_t pArg = *reinterpret_cast<const int32_t*>(data);
return pArg;
}
const void* Parcel::readInplace(size_t len) {
const void* data = mData + mDataPos;
// mDataPos += len;
finisWrite(len);
return data;
}
网友评论