"Turn" Pro Android Learning Note (Army Day): Service (6): Complex data parcel

Source: Internet
Author: User

Directory (?) [-]

    1. Custom Parcelable Class
    2. Aidl file
    3. Implementation of the service
    4. The implementation of the client
    5. Synchronous and asynchronous

The articles reproduced can only be used for non-commercial nature, and can not be accompanied by virtual currency, points, registration and other additional conditions. Reprint must indicate the source: http://blog.csdn.net/flowingflying/

The method in the previous StockQuote remote service interface is double GetQuote (String ticker);. The data type of a method in a remote service supports primitive types (primitive) such as int, supports string, charsequence, complex is type support list, MAP, but has some limitations in use, if we want to use a custom class as a type, Need to use parcelable. This note will learn how to perform complex data passing through parcelable encapsulation in a method call in a remote service.

The remote service is actually interprocess communication, so in connection with the interface, the object is not passed, but the data is copied to the original type. Java object is actually a pointer in C, Java is not without pointers, but in addition to the primitive type, all pointers, when it is a pointer, the developer does not feel the pointer and non-pointer differences, sometimes there is a wrong feeling, because Java no pointer. Because different processes have their own memory space, another process cannot manipulate the memory space of other processes, that is, objects that cannot manipulate other process memory spaces. The client and the remote service establish a connection to the Aidl interface that, when manipulated, passes the entire contents of the data, similar to the data we pass in the socket, the address (pointer/object) where we pass the data is meaningless, and we must pass the contents of the data.

Custom Parcelable Class

Parcel is a container for messages (data and objects) that can be passed in IBinder (that is, a connection to a remote service). Parcel is designed for high performance IPC transmission in Android, so we do not write parcel data directly into physical storage because changes in the data in parcel make other data unreadable. Parcelable is an interface, our custom data type, which needs to implement this interface in order to be passed as parcel in IBinder.

The following example is very simple, our custom data type person contains two data, one is int age, and the other is string name.

public class Personimplements Parcelable{
//"1" Custom type specifically contains the data, this example is age and name.
private int age = 0;
Private String name = NULL;

@Override
public int describecontents () {
return 0;
}

/ * "2" to implement the Parcelable interface, you need to implement Writetoparcel () and Readfromparcel () to write objects (data) to parcel, and to read objects from parcel. It should be noted that the order of writing and the order of reading must be consistent, since the parcel class is a fast serialization and deserialization mechanism, unlike bundles, which have no indexing mechanism, are linear data storage and reading.
* Note that readfromparcel () is not a overrider, but a method we provide ourselves, and if we do not provide it, we will
Private person (Parcel in) {
     *     Age = In.readint ();
     *     Name = In.readstring ();
     * }
* Given that the actual data types are more complex than small examples and are easy to read in code, we modeled Writetoparcel () and gave Readfromparcel () */
@Override
public voidWritetoparcel(Parcel out, int flag) {
Out.writeint (age); Write to age first
Out.writestring (name); Next write as Name
}

public voidReadfromparcel(Parcel in) {
Age = In.readint (); Read the age first, keep it in the same order as it was written
Name = In.readstring (); Next read name, keep and write in the same order
}

/* "3": Provides a constructor for creating an object from parcel, which is also the process of reading. This is set to private, prohibit external calls */
Private person (Parcel in) {

Readfromparcel (in);
}

This constructor is a convenient way for us to innovate related objects in the client and use them as parameters for calling methods in an interface connection.
Public person () {
}

/* Below are our custom methods in custom classes, this example simply provides the read/write of age and name */
public int getage () {
return age;
}

Public String GetName () {
return name;
}

public void Setage (int.) {
This.age = age;
}

public void SetName (String name) {
THIS.name = name;
}

/ * "4" the class that implements the Parcelable interface must have a static field called Creator, which implements the Parcelable.creator interface object. In the Java interface that is automatically generated by the Aidl file, IBinder calls Parcelable.creator to get the passed object: _arg1 = cn.wei.flowingflying.proandroidservice.Person.CREATOR.createFromParcel (data);  */
Public static final parcelable.creator<person> Creator = new Parcelable.creator<person> () {
@Override
Public person Createfromparcel (Parcel source) {
return new person (source);
See "3"
}

@Override
Public person[] NewArray (int size) {
return new Person[size];
}
};

}

Aidl file

We define PERSON.AIDL to parcelable, because we already have a person.java, so the system will no longer automatically generate the relevant Java code.

Package cn.wei.flowingflying.proandroidservice;
Parcelable person;

When PERSON.AIDL is defined, we can use that type in the interface definition. In non-primitive types, non-string types, other types in the interface as parameters need to describe the direction of the pass in, out, or inout.

Package cn.wei.flowingflying.proandroidservice;
Import Cn.wei.flowingflying.proandroidservice.Person;

Interface istockquoteservice2{
String GetQuote ( in string ticker, in person requester);
}

Implementation of the service

There is no difference between the implementation of the service and the previous remote service, except that the data types in the method are different. Below is a fragment of Stockquoteremoteservice2.java, in order to better interact with the user, the service will appear on the notification bar, detailed can download our source code for viewing. In addition, we need to define the service in Androidmanifest.xml.

Public class StockQuoteRemoteService2 extends Service{
public class Stockquoteserviceimpl extends istockquoteservice2.stub{
private int count = 0;
@Override
public string GetQuote (string ticker,Person Requester) throws RemoteException {
Return "Hello" + requester.getname () + "! Quote for "+ Ticker +" is "+ (20.0+ (count++));
}
}

... ...

@Override
Public IBinder Onbind (Intent arg0) {
return new Stockquoteserviceimpl ();
}
}

The implementation of the client

We create a new project to serve as a client. The client also needs to understand the interface and understand the definition of the parcelable person involved in the interface, So we need to copy the Istockquoteservice2.aidl,person.aidl and Person.java from the service.

And the previous client just connect the interface, the parameters of the calling method are different, the relevant code is as follows:

public class Mainactivity extends Activity {
Private IStockQuoteService2 stockService2 = null;
... ...
Private Serviceconnection Servconn = new Serviceconnection () {
@Override
public void onservicedisconnected (componentname name) {
... ...
StockService2 = null;
}

@Override
public void onserviceconnected (componentname name, IBinder service) {
... ...
StockService2 = IStockQuoteService2.Stub.asInterface (service);
}
};


private void Callservice () {
try{
person person = new person ();
Person.setage (25);
Person.setname ("flowingflying");
String response = Stockservice2.getquote ("WEI", person);
Toast.maketext (this, response, Toast.length_long). Show ();
}catch (RemoteException e) {
LOG.E ("Client2", e.tostring ());
}
}

}

Synchronous and asynchronous

The services learned here are synchronous because we make calls in the UI thread. If the service requires a large number of operations, we want to be able to run in the background, that is, the client calls the service in the background thread.

This post covers example code that can be downloaded in the Pro Android Learning: Android Service Small example.

RELATED Links: My Android development related articles

  

"Turn" Pro Android Learning Note (Army Day): Service (6): Complex data parcel

Related Article

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.