Service for Android Services (iii) about AIDL interprocess communication

Source: Internet
Author: User
Tags mremote

Reprint: http://www.cnblogs.com/zhangdongzi/archive/2012/01/09/2317197.html

A Basic knowledge the role of Aidl
On the Android platform, each app app is running in its own process space. Typically one process cannot access the memory space of another process (one app cannot access another), and if you want to communicate, you need to break down the object into a basic unit that the operating system understands, and Android provides aidl to handle it.
aidl (Android Interface Definition Language)is an IDL language used to generate code for interprocess communication (interprocess communication, IPC) between two processes on an Android device. You can use Aidl to generate serializable parameters if you want to invoke the operation of another process (such as a service) object in one process (for example, activity). In other words, it is the activity of my app that needs to invoke the service of another app. Of course, the activity and service of the same app can also be used between different processes, which can be set in service configuration, android:process= ": Remote" Use of AidlOfficial documentation specifically reminds us of when it is necessary to use AIDL: Only you allow clients to access your service from different applications for interprocess communication, as well as to handle multithreading in your service. (Too blunt, the components of different processes call it.) )

So how to make aidl? The following steps

1: create the. aidl file. Create a new file and save with . Aidl as a suffix, write interfaces and methods in this file, this is the same as our common Java Interface declaration, and the difference is to display the import complex type, even if the complex type object is within the same package. Java basic data types (int, long, char, Boolean, etc.), string and Charsequence, collection interface type list and map, no import required.

Like what:

Package Com.dongzi;
Interface istockquoteservice{
Double GetPrice (String ticker);
}

2: After creating the Aidl file, refresh the project, you will find that under the Gen package, the corresponding package appears under the same Java file as the Aidl file. Such as:

/** This file is auto-generated. Do not MODIFY. * Original File:d:\\mywordspace\\myphone\\src\\com\\dongzi\\istockquoteservice.aidl*/ PackageCom.dongzi; Public InterfaceIstockquoteserviceextendsAndroid.os.IInterface {/**Local-side IPC implementation stub class.*/     Public Static Abstract classStubextendsAndroid.os.BinderImplementsCom.dongzi.IStockQuoteService {Private Static FinalJava.lang.String descriptor = "Com.dongzi.IStockQuoteService"; /**Construct The stub at attach it to the interface.*/         PublicStub () { This. Attachinterface ( This, descriptor); }        /*** Cast an IBinder object to an com.dongzi.IStockQuoteService * interface, generating a proxy if nee         Ded. */         Public Staticcom.dongzi.IStockQuoteService asinterface (Android.os.IBinder obj) {if(obj = =NULL)) {                return NULL; } android.os.IInterface iin=(android.os.IInterface) obj.querylocalinterface (descriptor); if(((Iin! =NULL) && (iininstanceofcom.dongzi.IStockQuoteService )) {return((Com.dongzi.IStockQuoteService) iin); }            return Newcom.dongzi.IStockQuoteService.Stub.Proxy (obj); }         PublicAndroid.os.IBinder Asbinder () {return  This; } @Override Public BooleanOntransact (intCode, Android.os.Parcel data, android.os.Parcel reply,intflags)throwsandroid.os.RemoteException {Switch(code) { Caseinterface_transaction: {reply.writestring (descriptor); return true; }             CaseTransaction_getprice: {data.enforceinterface (descriptor);                Java.lang.String _arg0; _arg0=data.readstring (); Double_result = This. GetPrice (_ARG0);                Reply.writenoexception ();                Reply.writedouble (_result); return true; }            }            return Super. Ontransact (Code, data, reply, flags); }        Private Static classProxyImplementsCom.dongzi.IStockQuoteService {PrivateAndroid.os.IBinder Mremote; Proxy (Android.os.IBinder remote) {mremote=remote; }             PublicAndroid.os.IBinder Asbinder () {returnMremote; }             Publicjava.lang.String Getinterfacedescriptor () {returndescriptor; }             Public DoubleGetPrice (java.lang.String Ticker)throwsandroid.os.RemoteException {android.os.Parcel _data=Android.os.Parcel.obtain (); Android.os.Parcel _reply=Android.os.Parcel.obtain (); Double_result; Try{_data.writeinterfacetoken (descriptor);                    _data.writestring (ticker); Mremote.transact (Stub.transaction_getprice, _data, _reply,0);                    _reply.readexception (); _result=_reply.readdouble (); }                finally{_reply.recycle ();                _data.recycle (); }                return_result; }        }        Static Final intTransaction_getprice = (Android.os.IBinder.FIRST_CALL_TRANSACTION + 0); }     Public DoubleGetPrice (java.lang.String Ticker)throwsandroid.os.RemoteException;}

Aidl tool automatically generated so much code, in fact, we only need to know 3 is enough.

public static abstract class stub extends Android.os.Binder implements Com.dongzi.IStockQuoteService static abstraction inner stub

Private static class Proxy implements Com.dongzi.IStockQuoteService Aidl service proxy class

Public Double GetPrice (java.lang.String ticker) throws android.os.RemoteException; The interface that AIDL publishes is the interface method we define.

3: Store the Aidl file in other client applications, we serve as the server. Of course, we can also conveniently put this application as a client and server. In fact, the fundamental difference is to make the caller and the callee in different processes , and then add android:process= ": Remote" in the service. Eliminates the re-establishment of application client calls.

4:aidl just define a contract, we need a service here to provide services. So set up service MyService.

Two Actual combat

Now that we know some basic knowledge, let's start with the code. Suppose we need to invoke a service from another application in a process that provides a stock price query, or a GPS-positioned service.

and define a class that inherits our Aidl generated stub inner class and implements the method we aidl define

The code is as follows:

 PackageCom.dongzi;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.os.IBinder;Importandroid.os.RemoteException;ImportAndroid.util.Log; Public classMyServiceextendsService {Static FinalString tag= "MyService"; //define inner class Myserviceimpl inherit our Aidl file automatically generated inner class,//and implement the interface method of our Aidl file definition    Private classMyserviceimplextendsistockquoteservice.stub{@Override Public DoubleGetPrice (String Ticker)throwsremoteexception {log.e (TAG,"GetPrice"); return10.5; }} @Override Publicibinder onbind (Intent arg0) {//return to AIDL implementation        return NewMyserviceimpl (); } @Override Public voidOnDestroy () {LOG.E (TAG,"Release MyService"); Super. OnDestroy (); }}

We need to return our Aidl interface implementation object in the Onbind method so that other processes are called.

Of course, now that the Aidl and service are all defined, you need to set the Mainfest.xml in the

<service android:name= ". MyService "
android:process= ": Remote"
>
<intent-filter>
<action android:name= "Com.dongzi.IStockQuoteService"/>
</intent-filter>
</service>

On the client side in the same app, android:process= ": remote", represented in the application, when the service is needed, a new process is automatically created. And if it is android:process= "remote", there is no ":" semicolon, then the global process is created, and the process is shared by different applications.

So now the client is calling our service, the code is as follows:

 PackageCom.dongzi;Importandroid.app.Activity;ImportAndroid.content.ComponentName;ImportAndroid.content.Context;Importandroid.content.Intent;Importandroid.content.ServiceConnection;ImportAndroid.os.Bundle;ImportAndroid.os.IBinder;Importandroid.os.RemoteException;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public classMyyactivityextendsActivity {Static FinalString tag= "Myyactivity"; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);           Setcontentview (R.layout.main); Button Btncall=(Button) Findviewbyid (R.id.btncall); if(btncall!=NULL) Btncall.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//Binding a serviceBindmyservice ();        }               }); } istockquoteservice IService=NULL; PrivateServiceconnection conn=Newserviceconnection () {@Override Public voidonserviceconnected (componentname name, IBinder service) {//returns the Aidl interface object, which can then be called by the Aidl methodIservice=IStockQuoteService.Stub.asInterface (service); Doublevalue=0.0; Try{Value=iservice.getprice (""); }            Catch(RemoteException e) {log.e (TAG,"Call Error! ");            E.printstacktrace (); } log.e (TAG,"The return value is:" +value); } @Override Public voidonservicedisconnected (componentname name) {log.i (TAG,"Release service");              }       }; Private voidBindmyservice () {//Intent intent=new Intent ("Com.dongzi.IStockQuoteService");Intent intent=NewIntent ( This, MyService.class);           StartService (Intent);       Bindservice (Intent, Conn, context.bind_auto_create); } }

Start the service at the click of the button, and then bind the service. After connecting to the services, we will find that the method defined in the call Aidl is made, printed as follows:


The project structure is:

Service for Android Services (iii) about AIDL interprocess communication

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.