码迷,mamicode.com
首页 > 移动开发 > 详细

Using self-defined Parcelable objects during an Android AIDL RPC / IPC call

时间:2014-06-20 16:30:16      阅读:537      评论:0      收藏:0      [点我收藏+]

标签:des   android   style   class   blog   code   

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 Android” I’ve explained the basics on how inter-process communication can be implemented in Android. Now we will take a look at a specialized field in this area: Using Parcelables as parameters of an AIDL method.
As described in the previous post it is possible to either use primitive java types within a remote method signature or any class which implements the android.os.Parcelable interface. Using this interface it is possible to define arbitrarily complex data types which can be used as parameters or return values 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 as 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 an Activity which is using the AIDL IPC to retrieve such a message object to display the current time. The corresponding projects are called AIDLRemoteClientUsingParcelableObject for the client project (containing the Activity) and AIDLRemoteMessageServiceUsingParcelableObject for the server (containing the Service).
Because this example is just a modified version of the previous one I will only explain the Parcelable related parts in this 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 svn to check the project out and your allowed to reuse portions of this code as you wish.

Fundamentals of Parcels and Parcelables

In Android, Parcels are used to transmit messages. Unlike to the java serialization, the Parcels are implanted as high-performance containers for the Android inter process communication. By implementing the Parcelable interface you declare that it’s possible to transform (marshall) your class into a Parcel and back (demarshall). Because the Parcels are designed for performance you should always use Parcelables instead of using the java serialization (which would also be possible) when doing IPC in android. Even when you are communicating with Intents you can still use Parcels to pass data within the intent instead of serialized data which is most likely not as efficient as Parcels.

The Parcelable Interface

The android.os.Parcelable interface defines two methods which have to be implemented:

int describeContents()

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

void writeToParcel(Parcel dest, int flags)

his is the core method which is called when this object is to be marshalled to a parcel object. In this method all required data fields should be added to the “dest” Parcel so that it’s possible to restore 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 value 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, you may want to check if the flag is set and remove the references at this moment to free resources which are limited on mobile devices.

Furthermore it is necessary to provide a static CREATOR field in any implementation of the Parcelable interface. The type of this CREATOR must be of Parcelable.Creator<T>. This CREATOR will act as a factory to create objects during the demarshalling of the parcel. For this purpose, the Parcelable.Creator interface defines two methods where the type parameter T represents the Parcelable 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 you can extract the data fields in the same sequence as you put them into the Parcel during the writeToParcel method. These fields can then be used to create an 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 that we know what we have to implement when creating a class which implements the Parcelable interface, we can define our own message class which will be used in the example. Within the example source code, the MyParcelableMessage class is defined in the com.appsolut.example.aidlMessageServiceUsingParcelable package.

public class MyParcelableMessage 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 to make sure that the information stored there is 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 has 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 writeToParcel(Parcel outParcel, int flags) {
    outParcel.writeString(message);
    outParcel.writeInt(textSize);
    outParcel.writeInt(textColor);
    outParcel.writeInt(textTypeface.getStyle());
}

For the demarshalling, we need to 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 two methods:

public static final Parcelable.Creator<MyParcelableMessage> CREATOR = new Parcelable.Creator<MyParcelableMessage>() {

    @Override
    public MyParcelableMessage createFromParcel(Parcel in) {
        String message = in.readString();
        int fontSize = in.readInt();
        int textColor = in.readInt();
        Typeface typeface = Typeface.defaultFromStyle(in.readInt());
        return new MyParcelableMessage(message, fontSize, textColor, typeface);
    }

    @Override
    public MyParcelableMessage[] newArray(int size) {
        return new MyParcelableMessage[size];
    }
};

During the createFromParcel method we use the read methods which are provided in the Parcel to extract our state information. In 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’t be able to locate our self-defined MyParcelableMessage even if it implements the Parcelable interface. To propagate our implementation to the AIDL compiler, we need to define an aidl file which declares the class as Parcelable:

/* The package where the aidl file is located */
package com.appsolut.example.aidlMessageServiceUsingParcelable;

/* Declare our message as a class which implements the Parcelable interface */
parcelable MyParcelableMessage;

Like all aidl files, this file has to be 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 about it. This is done by an java like import statement where the full identifier of the class has to be used (package + class).

/* The package where the aidl file is located */
package com.appsolut.example.aidlMessageServiceUsingParcelable;

/* Import our Parcelable message */
import com.appsolut.example.aidlMessageServiceUsingParcelable.MyParcelableMessage;

/* The name of the remote service */
interface IRemoteParcelableMessageService {

    /* A simple Method which will 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, you have to provide the defined Parcelable classes to the client because the class files are required to instantiate the objects when performing the remote procedure call. In our example we just copied the .java file together with the corresponding .aidl files to the client project.

Summary and Further Reading

It is quite easy to define own model classes which are Parcelable. So you should always prefer parcels over the use of the default java serialization because the performance can be increased, which is important on mobile devices which might not always use the latest processor or be limited by other resources e.g. the memory. In addition to the performance enhancements, the possibility of using Parcelable model classes further enhances the capabilities of the Android IPC mechanism and increases the ease of use of the remote interface because multiple parameters can be combined into an object.

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

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

by Kevin Kratzer

Using self-defined Parcelable objects during an Android AIDL RPC / IPC call,布布扣,bubuko.com

Using self-defined Parcelable objects during an Android AIDL RPC / IPC call

标签:des   android   style   class   blog   code   

原文地址:http://www.cnblogs.com/savagemorgan/p/3796811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!