Process communication between Android (passing complex objects)

Source: Internet
Author: User

Process communication between Android (passing complex objects) completes serialization of complex objects

When passing complex data types in Android, it is possible to serialize the object by serializing it and providing an interface parcelable in Android.

The following serializes the objects that need to be transferred, first looking at the custom class person.

 PackageCom.example.service_parcelable_conmmute.bean;ImportAndroid.graphics.Bitmap;/*** Object Structure for transfer *@authorXinyuyu **/ Public classPerson {PrivateString name; PrivateString age; PrivateBitmap figure;  PublicPerson () {} PublicPerson (string name, String age, Bitmap) { This. Name =name;  This. Age =Age ;  This. Figure =Figure ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString getage () {returnAge ; }     Public voidsetage (String age) { This. Age =Age ; }     PublicBitmap getfigure () {returnFigure ; }     Public voidsetfigure (Bitmap figure) { This. Figure =Figure ; }}

This class is the general JavaBean contains some get/set methods, and all we have to do is pass the value of the object between processes. So the object is serialized, and a class is implemented below to accomplish the task.

Establish the Parcelableperson class to perform the serialization and deserialization of the person. The code is as follows:

 Public classParcelablepersonImplementsparcelable { person person=NewPerson ();  PublicPerson Getperson () {returnPerson ; }     Public voidSetperson (person person) { This. person =Person ; }     PublicParcelableperson (person person) { This. person =Person ; }     PublicParcelableperson (Parcel source) {Person.setname (source.readstring ());        Person.setage (Source.readstring ()); Person.setfigure (Bitmap) source.readparcelable (Bitmap.class. getClassLoader ())); } @Override Public intdescribecontents () {return0; } @Override Public voidWritetoparcel (Parcel dest,intflags)        {dest.writestring (Person.getname ());        Dest.writestring (Person.getage ());    Dest.writeparcelable (Person.getfigure (), parcelable_write_return_value); }         Public Static FinalParcelable.creator<parcelableperson> Creator =NewParcelable.creator<parcelableperson>() {@Override PublicParcelableperson Createfromparcel (Parcel source) {return NewParcelableperson (source); } @Override PublicParcelableperson[] NewArray (intsize) {            return NewParcelableperson[size]; }    };}

This code completes the serialization and deserialization of the person object, implementing the Parcelable interface to rewrite several methods (serialization and deserialization, respectively), Writetoparcel (Parcel dest, int flags) The completion is the serialization of the object

The parameter parcel is a container in which the object is put into the process of serialization. The Createformparcel (Parcel source) in creator is the deserialization that can return a complex object. The implementation of this write completes the serialization and deserialization of complex objects so that we can transfer them.

Complete the binding service and complete the communication in the process

Above we just completed the serialization of a complex object, and the next thing we do is build the service and complete the transfer.

The first thing we need to do is create a service, and create a service in Android to do it to implement service interfaces. Here is a service code for the sending object

 Public classServiceforsendobjectextendsService {Private Static FinalString MSG = "MESSAGE"; PrivateParcelableperson Parcelableperson; Privateperson person ; // =====================================Sendobject.stub Sendbinder =NewStub () {@Override PublicParcelableperson Getpersoninfo ()throwsremoteexception {log.i (MSG,"Call the Getpersoninfo () interface implementation to return a serialized object"); returnParcelableperson;    }}; // =====================================@Override Public voidonCreate () { person=NewPerson ("Xinyuyu", "25", Bitmapfactory.decodestream (Getresources (). Openrawresource (R.drawable.ic_launcher))); Parcelableperson=NewParcelableperson (person); Super. OnCreate (); LOG.I (MSG,"Callback OnCreate () Create service"); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {log.i (MSG,"Callback Onstartcommand () Start service"); return Super. Onstartcommand (Intent, flags, Startid); } @Override Public BooleanOnunbind (Intent Intent) {log.i (MSG,"Callback Onunbind Unbind Service"); return Super. Onunbind (Intent); } @Override Public voidOnDestroy () {log.i (MSG,"Callback OnDestroy Destruction Service"); Super. OnDestroy (); } @Override Publicibinder onbind (Intent Intent) {log.i (MSG,"Callback Onbind () method binding Service"); returnSendbinder; }}

The key to outputting some information from each stage in the code is to instantiate an object in the Oncreat () method and to serialize the object. The code between the split lines is the key code, note that a Sendobject.stub object is returned in IBinder (). And how is this class generated? We need to use the Aidl language in Android to define an interface when we are transferring between processes, so let's build a aidl file called SendObject. sendobject.aidl

 Package Com.example.service_parcelable_conmmute_service.aidl; Import Com.example.service_parcelable_conmmute.bean.ParcelablePerson; Interface SendObject {    Parcelableperson getpersoninfo ();}

Import in this interface will be an error, it is necessary to create a aidl file, the name is set to the same as the serialization class, here to do parcelableperson.aidl. The contents are as follows

Package Com.example.service_parcelable_conmmute.bean;

Parcelable Parcelableperson;

There is no mistake in completing this.

At this point you will find a Java file that is the same as your aidl name in the Gen directory, which is Sendobject.java. And the sendobject.stub we use is in it. Open this file and you'll see that Sendobject.stub is a class that implements the SendObject interface and inherits the Android.os.Binder class. This allows us to rewrite the SendObject method and implement the functionality. Is the code that divides the line directly.

 Public Static Abstract class extends  implements Com.example.service_parcelable_conmmute_service.aidl.SendObject

Also note that the service communication between the processes should change the properties of the Androidmanifest.xml file, as follows

<service android:name= "Com.example.service_parcelable_conmmute.service.ServiceForSendObject"android: Process= ": Remote" ><intent-filter>        <action android:name= "Com.example.service_parcelable_ Conmmute.service.SEND_OBJECT "/>            <category android:name=" Android.intent.category.DEFAULT "/>    </intent-filter></service>

This completes the implicit pass-through intent. With this, the server is finished. This is the time to run the code.

Start interface

After you click Initialize service, you can see the service start running

The red box is for our service.

Click on the two buttons to Logcat output information

The life cycle of this service can be seen from here.

Above we have completed the service side of the work, the following to do the client's completion.

The first thing we need on the client is to copy the Aidl files and entity classes that are written by the server to the project (together with the package name) as

Then all we have to do is complete the client's activity program. The connection between the two programs is our SendObject interface. Look at the code below

 Public classAextendsActivity {PrivateButton Show_button; PrivateTextView Show_name_age; PrivateImageView Show_image; PrivateButton Unbind_ser; PrivateSendObject SendObject; PrivateParcelableperson Parcelableperson; Privateperson person ; PrivateServiceconnection connection =Newserviceconnection () {//The service program calls the Onbind () method after the binding is established, returning a IBinder object@Override Public voidonserviceconnected (componentname name, IBinder service) {SendObject=SendObject.Stub.asInterface (service); Try{Parcelableperson=Sendobject.getpersoninfo (); person=Parcelableperson.getperson (); LOG.I ("", Person.getname ()); Show_name_age.settext (Person.getname ()+ "\ n" +person.getage ());                            Show_image.setimagebitmap (Person.getfigure ()); } Catch(RemoteException e) {e.printstacktrace (); }} @Override Public voidonservicedisconnected (componentname name) {LOG.I ("", "error");    }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.LAYOUT.A); Show_button= (Button) This. Findviewbyid (R.id.button1); Show_name_age= (TextView) This. Findviewbyid (R.id.textview1); Show_image= (ImageView) This. Findviewbyid (R.id.imageview1); Unbind_ser= (Button) This. Findviewbyid (R.id.button2); Show_button.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//implicit pass-through intentIntent Intent =NewIntent (); Intent.setaction ("Com.example.service_parcelable_conmmute.service.SEND_OBJECT");            Bindservice (Intent, connection, bind_auto_create);        }}); //Unbind (the service is automatically destroyed after the activity is destroyed)Unbind_ser.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {unbindservice (connection);    }                    }); }}

Bind the program with the service to use the Bindservice () method, see the parameters in the method, the first one is a intent, the second is a serviceconnection class, and the service to establish a connection to receive Onbind () transmitted data. From this method we get the object that is passed over. Running the client program

When you click the first button, a person object's information is displayed. This means that the data is transferred from the server.

Logcat Output Information

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.