Android Parcel object in a detailed

Source: Internet
Author: User

About the use of parcel

Before analyzing the parcel, we first introduce the related general use of parcel according to the analysis process.

The first is about the acquisition of parcel:

Parcel parcle = Parcel.Obtain();

Well, this feels familiar, and here we're guessing that the initialization of parcel is also initialized by its object pool. After getting the parcel object, the next step is to work. Well, I think it should introduce the role of parcel:

Actually see this article of everyone, should also do not need this science bar, haha. I intercept the following from the source notes:

*container for a message (data and object references) that can
* be sent through an ibinder. A Parcel can contain both flattened data
* That'll be unflattened on the other side of the IPC (using the various
* Methods here for writing specific types, or the general

As can be seen from this note, parcel is a container that can contain data or object references and can be used for the transfer of binders. It also supports serialization and deserialization after cross-process, while providing many ways to help developers with these functions. OK, it's almost clear here, parcel is mainly used for IPC communication. Of course, not just binder. This kind of cross-process communication.

Then back to this question, since parcel is a container, then you definitely need to pass data to it, yes, so after initializing parcel, you need to do the following:

parcel.writeInt(int val);

Pass in an int data to the parcel, followed by:

parcel.writeString(String val);

A string type of data is passed into the parcel.

Here are just a few examples of the two most common types of data, in fact parcel supports a lot of data types, as shown here:

After you have finished writing the data, you need to serialize the data:

parcel.marshall();

After a previous step, a byte array is returned, and the main IPC-related operations are centered around this byte array. At the same time, because parcel read and write is a pointer operation, this step involves the operation of native, so after the data is written, you need to manually point the pointer to the original location, that is, the following actions:

parcel.setDataPosition(0);

Here, parcel this step has not been finalized, think of the previous parcel obtain () method, we have reason to believe that parcel destruction should be the use of the corresponding recycle () method.

So here are:

parcel.recycle();

This parcel object is freed to complete half of the IPC operation. As for how to transfer the data in the past, it will not be expanded. Here on the other end of the IPC, the parcel gets processed.

After the operation of the IPC, it is generally read that the byte array was previously serialized, so the first thing to do is to perform a deserialization operation, that is, the following operation:

parcel.unmarshall(byte[] data, int offest, int length);

The parameters are the byte array, the read offset, and the length of the array.

At this point the parcel is a normal parcel object, then we can get the data we deposited before in order to obtain, namely:

parcel.readInt();

And

parcel.readString();

Once read, it is also a parcel recycle operation:

parcel.recycle();

The above is the general use of parcel, get some friends do not quite know the use of parcel scenes, in fact, the most common, after we write Aidl interface, The IDE automatically generates a corresponding. java file, the Java file is actually used for aidl communication, in this implementation, the data transfer is the use of parcel, of course, there are other application scenarios, here only to say a common practice of everyone.

On the implementation of parcel

As mentioned before, the use of parcel for Java developers, is still relatively unfamiliar, like a pointer to the operation, so the basic can be determined that the Java layer for parcel processing is only an encapsulation agent, the actual implementation in C/s native. In this case, we should think that the use of parcel also involves the use of JNI. So our current idea is to find parcel's three-layer code (JAVA-JNI-C) in the source.

My specific approach is to use everything directly in the source directory to search for parcel, and then according to the previous idea of the package export, my analysis is based on the following several packages of implementation:

Java layer:

\frameworks\base\core\java\android\os

Jni:

\frameworks\base\core\jni

Native

\frameworks\native\libs\binder

Then import the files in these packages for easy retrieval:

Based on the order in which we use them, we first need to get a parcel to see the Java Layer implementation:

 /** * Retrieve A new Parcel object from the pool. *  /public static Parcel obtain () { final parcel[] pool = sownedpool; synchronized (pool) {Parcel p; For (int i=0; i<pool_size; i++) {p = pool[i]; if (P! = null) {pool[i] = null; if (debug_recycle) {p.mstack = new RuntimeException ();} return p;} }} return new Parcel (0);}              

As can be seen from the annotations, the initialization of parcle is primarily done using an object pool, which can improve performance and memory consumption. The first thing to be clear is that there are two pools defined in the source code:

    private static final int POOL_SIZE = 6; private static final Parcel[] sOwnedPool = new Parcel[POOL_SIZE]; private static final Parcel[] sHolderPool = new Parcel[POOL_SIZE];

From the name can also be seen, the role of different pools, sownedpool this pond is mainly used to store parcel, obtain () method will first go to retrieve the parcel object in the pool, if you can take out parcel, then the first this parcel back, This position is also empty. If the pool does not exist now, then create a new parcel object directly. The implementation here is treated the same as the message in handler.

After we understand the acquisition, the more concerned is how to create a new parcel object, which is the new process, then look at the parcel construction method here:

private Parcel(int nativePtr) {        if (DEBUG_RECYCLE) {            mStack = new RuntimeException(); } //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack); init(nativePtr); }

As you can see, here the parameter name is called: NativePtr, this everyone is more familiar with, PTR, refers to a pointer, here is a package, need to continue to look into the implementation:

private void init(int nativePtr) {        if (nativePtr != 0) { mNativePtr = nativePtr; mOwnsNativeParcelObject = false; } else { mNativePtr = nativeCreate(); mOwnsNativeParcelObject = true; } }

Here we first check the parameters, because the initialization of the parameters passed in is 0, then directly execute Nativecreate (), and the flag bit mownsnativeparcelobject to true, indicating that the parcel has been created in native.

Here Ativecreate () is a native method, its implementation has been switched to native environment, then we will be the analysis from the JNI, after retrieval, in the JNI code, in fact, is now the following function:

static jint android_os_Parcel_create(JNIEnv* env, jclass clazz){    Parcel* parcel = new Parcel();    return reinterpret_cast<jint>(parcel);}

This is a JNI implementation, first of all called the initialization of the native, and returns a pointer to the object that operates on it:

Parcel::Parcel(){    initState();}

is a C + + construction method, on the destructor, for the time being, where the init implementation is:

void Parcel::initstate () {merror = No_error;    Mdata = 0;    Mdatasize = 0;    Mdatacapacity = 0; Mdatapos = 0; ALOGV ("initstate Setting data size of%p to%d\n", this , mdatasize); ALOGV ("initstate Setting data pos of%p to%d\n", this , mdatapos); mobjects = NULL; mobjectssize = 0; mOb Jectscapacity = 0; mnextobjecthint = 0; Mhasfds = false; Mfdsknown = true; Mallowfds = true; mown ER = NULL;}                

As you can see, the initialization of parcel only initializes some data values in the native layer.

After the initialization is complete, the operation pointer is returned. This completes the initialization of the parcel.

After initialization is complete, the data can be written, first writing an int data, the Java layer is implemented as follows:

/**     * Write an integer value into the parcel at the current dataPosition(),     * growing dataCapacity() if needed.     */    public final void writeInt(int val) { nativeWriteInt(mNativePtr, val); }

As you can see, here the Java layer is purely an encapsulation of the native implementation, when the analysis comes to JNI:

static void android_os_Parcel_writeInt(JNIEnv* env, jclass clazz, jint nativePtr, jint val) {    Parcel* parcel = reinterpret_cast<Parcel*>(nativePtr);    const status_t err = parcel->writeInt32(val);    if (err != NO_ERROR) { signalExceptionForError(env, clazz, err); }}

Here we have to pay special attention to two parameters, one is the previous pointer and the need to save the int data, the two values are:

val

The first is based on this pointer, here, the pointer is actually an integer address value, so it is feasible to use a strong turn to convert the int value to the parcel type pointer, and then use this pointer to manipulate the native parcel object, namely:

const status_t err = parcel->writeInt32(val);

Notice here that we are writing a 32-bit int value, this point must be noted, 32 bits, 4 bytes.

Go inside to see the implementation:

val){    return writeAligned(val);}

As you can see, this is actually called:

writeAligned(val);

To write the data, here to understand the meaning of the next align, is actually an alignment write, how to align the method, look at:

template<class T>status_t Parcel::writeAligned(T val) {    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(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;}

In this method, the first is an assertion check, then a size value for the input parameter, plus the previously moved position, to determine whether the Pacel defined capacity value mdatacapacity.

If the ability value is exceeded, then the capacity value is expanded directly, the value of the expansion is the size of the Val value, for example, the int value is 32bit, then the increment of 4 bytes, The returned result is the state value, if there is no error, the use of goto statement execution, The goto statement here moves the pointer to the endpoint as long as it is a pointer operation, and then writes the size value of Val. Here you can see the meaning of this function because it writes the size value of the T type value, regardless of whether it exceeds the capability value.

Here, Parcel writes a value of type int.

The same idea, we can refer to the above analysis, continue to parcel a routine use of analysis, I was to want to all the implementation of the analysis out, but later found that the general idea is similar, so write, will come out a lot of nonsense, so the next analysis, if you are interested, Continue the analysis, welcome to discuss together!

Also, during the analysis, I explored the jni invocation of Android, in a nutshell, how does Java use the Java layer's native method to find the corresponding Jni method after the JVM environment switches to the native environment? Because I don't know much about the implementation of the JVM, I can only analyze it from the code level of the Android source, at least in Android:

After switching to the native environment, in fact, the mapping of these two functions is managed by a multi-array, as follows:

StaticConst Jninativemethod Gparcelmethods[] = {{"Nativedatasize","(i) I", (void*) Android_os_parcel_datasize}, {"Nativedataavail","(i) I", (void*) Android_os_parcel_dataavail}, {"Nativedataposition","(i) I", (void*) Android_os_parcel_dataposition}, {"Nativedatacapacity","(i) I", (void*) Android_os_parcel_datacapacity}, {"Nativesetdatasize","(II) V", (void*) Android_os_parcel_setdatasize}, {"Nativesetdataposition","(II) V", (void*) Android_os_parcel_setdataposition}, {"Nativesetdatacapacity","(II) V", (void*) Android_os_parcel_setdatacapacity}, {"Nativepushallowfds","(IZ) Z", (void*) Android_os_parcel_pushallowfds}, {"Nativerestoreallowfds","(IZ) V", (void*) Android_os_parcel_restoreallowfds}, {"Nativewritebytearray","(I[bii) V", (void*) Android_os_parcel_writenative}, {"Nativewriteint","(II) V", (void*) Android_os_parcel_writeint}, {"Nativewritelong","(IJ) V", (void*) Android_os_parcel_writelong}, {"Nativewritefloat","(IF) V", (void*) Android_os_parcel_writefloat}, {"Nativewritedouble","(ID) V", (void*) Android_os_parcel_writedouble}, {"Nativewritestring","(iljava/lang/string;) V", (void*) Android_os_parcel_writestring}, {"Nativewritestrongbinder","(Ilandroid/os/ibinder;) V", (void*) Android_os_parcel_writestrongbinder}, {"Nativewritefiledescriptor","(Iljava/io/filedescriptor;) V", (void*) Android_os_parcel_writefiledescriptor}, {"Nativecreatebytearray","(I) [B], (void*) Android_os_parcel_createbytearray}, {"Nativereadint","(i) I", (void*) Android_os_parcel_readint}, {"Nativereadlong","(I) J", (void*) Android_os_parcel_readlong}, { "NativeReadFloat", Span class= "hljs-string" > "(I) F", (void*) Android_os_parcel_readfloat}, {" nativereaddouble ", " (I) D ", (void*) android_os_ Parcel_readdouble}, { "nativereadstring",  "(I) Ljava/lang/ String; ", (void*) android_os_parcel_readstring}, {void*) Android_os_parcel_readstrongbinder}, { "Nativereadfiledescriptor",  "(I) Ljava/io/filedescriptor;", (void*) android_os_parcel_ Readfiledescriptor},........              

There are many mapping relationships, so the function can be mapped to the corresponding, but there is a point, this thing is when, and where to call, this expansion is a long story, so this paragraph I also do not analyze, we know there is such a thing OK, Of course, welcome to discuss together!

Android Parcel object in a detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.