Android Learning Note 26. Call service across processes (Aidl service)

Source: Internet
Author: User
Tags getcolor

Invoking Service (aidl service) across processesFirst, Aidl Service 1. What is Aidl Service?Aidl, that is, Android Interface definition Language. Is Android used to define the remote interface, the syntax of the Aidl interface definition language is relatively simple, the interface definition language is not a real programming language, it is just Defines a communication interface between two processes . The syntax of AIDL is similar to the Java interface, but there are several differences:(1) The source code for the AIDL definition interface must be. Aidl end;(2) The Aidl interface uses the data type, except for the basic type, String, List, Map, charsequence, all other types need to be guided, even if they are in the same package also need to guide the package. in an Android system, because each application is running in its own process (starting an app that starts a process), there is generally no direct data exchange between processes. So, in order to implement the processofinterprocess communiocation, referred to as IPC, Android provides a aidl Service. 2. Remote Servicecorresponding to the local service is the remote service, where one application (process) can access the service component of another application, the former we callClient, the latter forService side,and the Client Access server is throughAidl Interfaceachieve communication with each other. Through the previous articles we know thatwhen a client accesses a service, Android does not directly return the service object to the client, but instead passes the service's proxy object (the IBinder object) through the service'sOnbind () methodReturn to client, and therefore,The implementation class for the Aidl remote interface of Android is the IBinder implementation class. When the client obtains the proxy for the IBinder object of the remote service, the client process can use the IBinder object to callback the properties or methods of the remote service to enable interprocess communication. IBinder object returned by 3.Servicewhen the visitor (client) invokes the Bindservice () method to bind to the specified service, it is different for binding the ground service or the IBinder object that the remote Service,service is bound to return. (1) Bind the ground service: the Onbind () method of the local service will direct the IBinder object itself The second argument to the Onserviceconnected method of the Serviceconnection object passed to the client;(2) Bind remote service: The Onbind () method of the remote service simply converts the IBinder object's proxy The second argument to the Onserviceconnected method of the Serviceconnection object passed to the client. how the 4.AIDL interface workswhen a. Aidl aidl interface source file (such as/SRC/COM/ANDROID_AIDLSERVICE/ICAT.AIDL) is implemented in the project, We can generate the required Icat.java interface files in two ways: one is to use the Aidl.exe tool under the Platform-tools sub-record in the Android SDK installation directory, and the ADT tool automatically generates the implementation for the Aidl interface (path: gen/ Com.example.android_aidlservice/icat.java). The Icat.java interface consists of a stub inner class that implements the IBinder, ICat two interfaces, This stub class will act as the callback class for the remote service---it implements the IBinder interface, and therefore can be used as the return value of the service's Onbind () method .      second, the process of communication between the development of ideas 1. Service-side-remote service development(1) Define a AIDL interface, file name is Xxx.aidl, save to the path where the source code,as/src/com/android_aidlservice/icat.aidl;Package Com.example.android_aidlservice;Interface ICat{String GetColor ();double Getweight ();}where Com.example.android_aidlservice is the package name in which it resides. (2) Defining a service implementation class and implementing an internal class that inherits from the stub implements the ICat interface and implements the IBinder interface. The Onbind () method of the service returns an instance of the IBinder object that is a subclass of Icat.stub. private Catbinder Catbinder;Public class Catbinder extends Stub{    ......}@OverridePublic IBinder Onbind (Intent arg0){return catbinder;}(3) Configure the service in the Androidmainfest.xml project file<application ....><!--define a service component --<service android:name= ". Aidlservice "><intent-filter><action android:name= "Com.example.sercie.AIDL_SERVICE" ></action></intent-filter></service></application> 2. Client Development Ideas(1) Define a AIDL interface, file name is Xxx.aidl, save to the path where the source code, such as/src/com/android_aidlservice/icat.aidl;Package Com.example.android_aidlservice;Interface ICat{String GetColor ();double Getweight ();}where Com.example.android_aidlservice is the package name where the. aidl file is copied from the service segment's Aidl interface file to the client app. (2) Create the Serviceconnection object and add the following code to the Onserviceconnected method of the Serviceconnection object:Catservice = ICat.Stub.asInterface (service);where Catservice returns the proxy for the IBinder object for the service's Onbind () method. (3) using the Serviceconnection object as a parameter, call the context's Bindservice () method to bind and start the remote service. third, the realization of the source code 1. Service-side(1) Define a service implementation class-/src/com/example/android_service/aidlservice.java
Package Com.example.android_aidlservice;import Java.util.timer;import Java.util.timertask;import Com.example.android_aidlservice. Icat.stub;import Android.app.service;import Android.content.intent;import Android.os.ibinder;import Android.os.remoteexception;public class Aidlservice extends Service {//1. Declaring a IBinder object, timer object private Catbinder Catbinder; private timer timer; 2. Define a two array with two private variables of the privately String color; private double weight; string[] colors = new string[]{"Black", "yellow", "Red"}; Double[] Weigths=new double[]{2.3,3.1,1.58}; 3. Inherit Stub, also implement the ICat interface, and implement the IBinder interface public class Catbinder extends stubs {@Override public String GetColor () throws Rem  oteexception {return color;  } @Override public Double Getweight () throws remoteexception {return weight;  }}//4. Call this method when the service is created @Override public void OnCreate () {super.oncreate ();  A. Instantiate a Catbinder object catbinder = new Catbinder (); B. Tasks performed by the service: randomly change the value of the color, weight property within the service component Timer.schedule (new TimerTask () {@Override PUBlic void Run () {int rand= (int) (Math.random ());    Color=colors[rand];    Weight = Weigths[rand];   System.out.println ("-----------" +rand); }}, 0, 800); /*5. When a visitor starts a service using the Bindservice () method, the method is used to return the Catbinder object * (1) in the case of binding the ground service,  The Catbinder object is passed directly to the client's Serviceconnection object; * (2) in the case of a remote service binding, only the proxy of the Catbinder object is passed the second parameter of the * Onserviceconnection method of the client's Serviceconnection object */@Override public IBinder Onbind (Intent Intent) {return catbinder;}//6. Callback This method closes the service @Override public void OnDestroy () {Timer.cancel ( ); }}
(2) Configure the service in the Androidmanifest file
<?xml    Version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "Http://schemas.android.com/apk/res/android"        Package= "Com.example.android_aidlservice" android:versioncode= "1" android:versionname= "1.0" > <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <application android:allowbackup=" tr UE "android:icon=" @drawable/ic_launcher "android:label=" @string/app_name "android:theme=" @style/appth EME "> <service android:name=". Aidlservice "android:exported=" true "> <intent-filter> <action android:n Ame= "Com.example.service.AIDL_SERVICE"/> </intent-filter> </service> </application& Gt;</manifest> 
2. Client(1) Define an Activity implementation class-/src/com/example/android_service/aidlclient. Java
Package Com.example.android_aidl_service;import Android.app.activity;import Android.app.service;import Android.content.componentname;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.os.remoteexception;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;public Class  Aidlclient extends Activity {private ICat catservice;//declares a ICat object private Button get; private EditText color,weight; 1. Create a Serviceconnection object private serviceconnection conn=new serviceconnection () {@Override public void onserviceconnected (componentname name, IBinder service) {//proxy for the object that gets the Onbind method of the remote service Catservice = ICat.Stub.asInterf  Ace (Service);  } @Override public void onservicedisconnected (componentname name) {catservice=null;  } }; 2. Bind the remote service and get its contents @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (SavedinstanCestate);  A. Get the activity Main interface component Setcontentview (R.layout.main);  get= (Button) Findviewbyid (r.id.get);  Color= (EditText) Findviewbyid (R.id.color);   weight= (EditText) Findviewbyid (r.id.weight);  B. Create the Intent of the service that you want to bind and set its Action property (that is, specify which remote service to start) Intent intent=new Intent ();  Intent.setaction ("Com.example.service.AIDL_SERVICE");  C. Bind and start the remote Service bindservice (intent,conn,service.bind_auto_create);   D. Get remote service Data Get.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View v) through the agent of the IBinder object     {try {Color.settext (Catservice.getcolor ());    Weight.settext (Catservice.getweight () + "");    } catch (RemoteException e) {e.printstacktrace (); }   }  });  //3. Call this method when exiting activity, unbind the remote service @Override protected void OnDestroy () {Super.ondestroy (); This.unbindservice (conn); }}
(2) Configure the activity in the Androidmanifest file
<?xml    Version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "Http://schemas.android.com/apk/res/android"        Package= "Com.example.android_aidl_service" android:versioncode= "1" android:versionname= "1.0" > <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <application android:allowbackup=" t Rue "android:icon=" @drawable/ic_launcher "android:label=" @string/app_name "android:theme=" @style/appt Heme "> <activity android:name=". Aidlclient "android:label=" @string/app_name "> <intent-filter> <action an Droid:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest> 
effect: Run the client program and click the "Get Remote Service Data" button in the program interface to enable the client to read the remote service functionality.

Android Learning Note 26. Call service across processes (Aidl service)

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.