Using self-defined parcelable objects during an Android aidl RPC/IPC call

Source: Internet
Author: User

Using self-defined parcelable objects during an Android aidl RPC/IPC call

In my previous post "Using the Android Interface Definition Language (aidl) to make a Remote Procedure call (RPC) in Andro ID "I ' ve explained the basics on how inter-process communication can is implemented in Android. Now we'll take a look at a specialized field in this area:using parcelables as parameters of a aidl method.
As described in the previous post it's possible to either use primitive Java types within a remote method signature or an Y class which implements the Android.os.Parcelable interface. Using this interface it's possible to define arbitrarily complex data types which can be used as parameters or return Val UEs of methods during a remote method call.
I ' ve created a modified version of the first example app to give you a basic example which relies on a Parcelable object a S a method return value.
The example consists of a Service which generates a Parcelable message object containing the current system time and text Appearance values such as the color, the size and the style. In the second part of the example you can find a Activity which are using the Aidl IPC to retrieve such a message object T o Display the current time. The corresponding projects is called Aidlremoteclientusingparcelableobject for the client project (containing the Activit Y) and Aidlremotemessageserviceusingparcelableobject for the server (containing the Service).
Because This example is just a modified version of the previous one I would only explain the parcelable related parts in th Is post. If you encounter trouble Understanding the context, please refer to the first posting on Aidl.
As always, you can browse or download the source code of the example App at our SVN repository at Google code (http://code. google.com/p/android-aidl-ipc-rpc-example/) or use an SVN to check for the project outand your allowed to reuse portions of this code as you wish.

Fundamentals of Parcels and Parcelables

In Android, Parcels is used to transmit messages. Unlike to the Java serialization, the Parcels is implanted as high-performance containers for the Android Inter process C Ommunication. By implementing the Parcelable interface your declare that it's possible to transform (Marshall) your class into a Parcel a nd back (demarshall). Because The Parcels is designed for performance all should always use parcelables instead of using the Java serialization (which would also is possible) when doing IPC in Android. Even when is communicating with Intents you can still use Parcels to pass data within the intent instead of serialize D data which is the most likely not as efficient as Parcels.

The parcelable Interface

The Android.os.Parcelable interface defines and methods which has to be implemented:

int describecontents ()

This method can is used to give additional hints on how to process the received parcel. For example, there could is multiple implementations of an Interface which extends the parcelable Interface. When such a parcel is received, the This method can and be to determine which object implementation needs to be instantiated.

void int flags)

The

He is the core method, which is called, the This object was to be marshalled to a parcel object. In this method all required data fields should is added to the " dest " Parcel So, it's possible to Res Tore the state of the object within the receiver during the demarshalling. The " flags " parameter indicates if the marshalling was triggered because the object becomes a return valu E of a remote method (if that's the case, the parameter is set to Parcelable. Parcelable_write_return_value ). If your model object contains references which could hinder the garbage collector from freeing the resources, your may want To check if the flag was set and remove the references at this moment to free resources which be limited on mobile device S.

Furthermore it is necessary to provide a static CREATOR field in any implementation of the Parcelable interface. The type of this CREATOR must is of parcelable.creator<t>. This CREATOR would act as a factory to create objects during the demarshalling of the parcel. For this purpose, the Parcelable.creator interface defines the methods where the type parameter T represents the PARCELABL E object:

T Createfromparcel (Parcel source)

This method is called during the demarshalling of the object. The parameter source represents the parcel which contains the data of the corresponding object. During This method can extract the data fields in the same sequence as you put them into the Parcel During the WriteTo Parcel method. These fields can and is used to create a instance of the object.

T[] NewArray (int size)

This method returns just an empty array of the object with a given size.

Defining the Parcelable Message Class

Now so we know what we had to implement when creating a class which implements the Parcelable interface, we can define Our own message class which is used in the example. Within the example source code, the Myparcelablemessage class is defined in the Com.appsolut.example.aidlMessageS Erviceusingparcelable package.

 public  class  myparcelablemessage Span style= "color: #0000ff;" >implements   parcelable { private  final      String message;  private  final  int   textSize;  private  final  int   TextColor;  private  final  Typeface Texttypeface; 

These fields represent the state of the message. We have a to do sure that the information stored there are not lost during the marshalling or demarshalling process. For the marshaling process, we need to implement the methods defined in the Parcelable interface:

The Describecontents Method
 Public int describecontents () {    return 0;}

Because our content have nothing special about it we can just return a zero.

The Writetoparcel Method

The Writetoparcel method is implemented quite easy as well. The Parcel interface contains methods to write primitve Java types such as String, int, etc. We can use these methods to store the object state within the parcel.

 Public void int flags) {    outparcel.writestring (message);    Outparcel.writeint (textSize);    Outparcel.writeint (textcolor);    Outparcel.writeint (Texttypeface.getstyle ());}

For the demarshalling, we need-remember the sequence in which we have stored the ' fields ' in the parcel.

The Parcelable.creator Creator field

The CREATOR field is required for the demarshalling. As previously described, the Parcelable.creator interface requires us to implement both methods:

 Public Static FinalParcelable.creator<myparcelablemessage> Creator =NewParcelable.creator<myparcelablemessage>() {@Override Publicmyparcelablemessage Createfromparcel (Parcel in) {String message=in.readstring (); intFontSize =In.readint (); intTextColor =In.readint (); Typeface Typeface=Typeface.defaultfromstyle (In.readint ()); return Newmyparcelablemessage (Message, FontSize, TextColor, typeface); } @Override PublicMyparcelablemessage[] NewArray (intsize) {        return NewMyparcelablemessage[size]; }};

During the Createfromparcel method we use the read methods which is provided in the Parcel to extract our state informati On. The end we create a new Myparcelablemessage object with the corresponding state.

The NewArray method just returns an empty array.

Defining the Aidl Files

The Aidl Complier won ' is able to locate our self-defined myparcelablemessage even if it implements the Parcelable Interf Ace. To propagate our implementation to the Aidl compiler, we need to define an aidl file which declares the class as Parcelabl E:

/** * package com.appsolut.example.aidlMessageServiceUsingParcelable; /*  */parcelable myparcelablemessage;

Like all aidl files, this file have to is in the same folder as the class file.

Within the Aidl file of the remote interface we have to import our parcelable message so that the Aidl compiler knows Abou T it. This was done by a Java like import statement where the full identifier of the class have to being used (Package + Class).

/*The package where the Aidl file is located*/ Packagecom.appsolut.example.aidlMessageServiceUsingParcelable;/*Import our parcelable message*/ImportCom.appsolut.example.aidlMessageServiceUsingParcelable.MyParcelableMessage;/*The name of the remote service*/InterfaceIremoteparcelablemessageservice {/*a simple Method which would return A message * The Message object implements the Parcelable interface*/myparcelablemessage getMessage ();}
Using the parcelable Class in the Client

In addition to the Aidl remote interface description and you had to provide the defined parcelable classes to the client Bec Ause the class files is required to instantiate the objects when performing the remote procedure call. Example we just copied the. java file together with the corresponding. aidl files to the client project.

Summary and further Reading

It's quite easy to define own model classes which is parcelable. So-should always prefer parcels-the-use of the default Java serialization because the performance can increase D, which is important on mobile devices which might not always use the latest processor or being limited by other resources E . G. The memory. In addition to the performance enhancements, the possibility of using parcelable model classes further enhances the Capabi Lities of the Android IPC mechanism and increases the ease of use of the remote interface because multiple parameters can Be combined to an object.

If you want to get more information on this topic I suggest you refer to the following links:

    • Android Interface Definition Language (aidl)
    • Android Interface Definition Language (aidl): Passing Objects
    • Android API Reference:parcel
    • Android API reference:parcelable
    • Android API Reference:Parcelable.Creator
    • Android API Reference:ibinder

http://www.app-solut.com/blog/2011/05/using-self-defined-parcelable-objects-during-an-android-aidl-rpc-ipc-call/

by Kevin Kratzer

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.