Android study note 26. Cross-process call Service (AIDL Service) and androidaidl

Source: Internet
Author: User
Tags getcolor

Android study note 26. Cross-process call Service (AIDL Service) and androidaidl
Cross-process call Service (AIDL Service) I. AIDL Service1. What is AIDL Service?AIDL, that is, Android Interface Definition Language. android is used to define remote interfaces. the syntax of the AIDL Interface Definition Language is relatively simple. This interface definition language is not a real programming language, but a communication interface between two processes. The syntax of AIDL is similar to that of the Java interface, but there are the following differences: (1) the source code of the AIDL-defined interface must be. end of aidl; (2) data types used in the AIDL interface. Except for basic types, such as String, List, Map, and CharSequence, all other types need to be imported, even if they need to export packages in the same package. In the Android system, because each application is running in its own process (starting an Application means starting a process), data exchange between processes is generally unavailable. Therefore, in order to implement interprocess communiocation (IPC), Android provides the AIDL Service.2. remote ServiceA remote Service corresponds to a local Service, that is, an application (process) can access the Service components of another application. The former is called a client and the latter is a server, the client accesses the server through the AIDL interface to communicate with each other. Through the previous articles, we know that when the client accesses the Service, Android does not directly return the Service object to the client, but uses the Service proxy object (IBinder object) through the onBind () of the Service () the method is returned to the client. Therefore, the Implementation class of the Android AIDL remote interface is the IBinder implementation class. After the client obtains the proxy of the IBinder object of the remote Service, the client process can call back the attributes or methods of the remote Service through the IBinder object to implement inter-process communication.3. IBinder object returned by the ServiceWhen a visitor (client) calls the bindService () method to bind and start a specified Service, the IBinder object returned by the Service is different for local Service binding or remote Service binding. (1) bind local Service: the onBind () method of the local Service directly transmits the IBinder object itself to the second parameter of the onServiceConnected method of the ServiceConnection object of the client; (2) Bind Remote Service: the onBind () method of the remote Service is only the second parameter of the onServiceConnected method of the ServiceConnection object of the client through the proxy of the IBinder object.4. AIDL Interface Working PrincipleWhen. source files of aidl APIs (such as/src/com/android_aidlservice/ICat. aidl), we can generate the required ICat in two ways. java interface file: first, use the aidl.exe tool in the platform-toolssubdirectory of the Android sdkinstallation directory; second, the ADT tool automatically generates an implementation for the AIDL interface (Path: gen/com. example. android_aidlservice/ICat. java ). ICat. the java Interface contains a Stub internal class that implements the IBinder and ICat interfaces. The Stub class will be used as the callback class of the remote Service-it implements the IBinder interface, therefore, it can be used as the return value of the onBind () method of the Service.2. inter-process communication development ideas1. Server-remote Service development(1) define an AIDL interface named xxx. aidl: The Path to the source code, for example,/src/com/android_aidlservice/ICat. aidl; package com. example. android_aidlservice; interface ICat {String getColor (); double getWeight () ;}among them, com. example. android_aidlservice is the package name. (2) define a Service implementation class and implement an internal class that inherits from Stub to implement the ICat interface and implement the IBinder interface. The IBinder object returned by the onBind () method of the Service is an instance of the subclass of ICat. Stub. Private CatBinder catBinder; public class CatBinder extends Stub {......} @ Overridepublic IBinder onBind (Intent arg0) {return catBinder;} (3) in AndroidMainfest. configure the Service in the 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 an AIDL interface named xxx. aidl: The Path to the source code, for example,/src/com/android_aidlservice/ICat. aidl; package com. example. android_aidlservice; interface ICat {String getColor (); double getWeight () ;}among them, com. example. android_aidlservice is the package name. the aidl file is copied from the AIDL interface file of the Service segment to the client application. (2) create a ServiceConnection object and add the following code to the onServiceConnected method of the ServiceConnection object: catService = ICat. stub. asInterface (service); where catService is the onBind () method of Service and the proxy of the IBinder object is returned. (3) using the ServiceConnection object as the parameter, call the bindService () method of Context to bind and start the remote Service.Iii. Source Code Implementation1. Server(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. declare An IBinder object and a Timer object private CatBinder catBinder; private Timer timer; // 2. define two arrays and two private variables: private String color; private double weight; String [] colors = new String [] {"black", "yellow", "Red "}; double [] weigths = new double [] {2.3, 3.1, 1.58}; // 3. inherits stub, implements the ICat interface, and implements the IBinder interface public class CatBinder extends Stub {@ Override public String getColor () throws RemoteException {return color ;} @ Override public double getWeight () throws RemoteException {return weight ;}}// 4. this method is called when the Service is created @ Override public void onCreate () {super. onCreate (); //. instantiate a CatBinder object catBinder = new CatBinder (); // B. tasks completed by the service: randomly change the value of the color and weight attribute in the Service component timer. schedule (new TimerTask () {@ Override public void run () {int rand = (int) (Math. random () * 3); color = colors [rand]; weight = weigths [rand]; System. out. println ("-----------" + rand) ;}, 0,800);}/* 5. when a visitor uses the bindService () method to start a Service, this method is used to return the catBinder object * (1) when the local Service is bound, the catBinder object will be directly transmitted to the ServiceConnection object of the client; * (2) when binding a remote Service, only pass the proxy of the catBinder object to the second parameter of the * onServiceConnection Method */@ Override public IBinder onBind (Intent intent) {return catBinder;} // 6. call back this method to disable 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="19" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <service android:name=".AidlService"              android:exported="true">            <intent-filter>                <action android:name="com.example.service.AIDL_SERVICE"/>            </intent-filter>        </service>    </application></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; // declare an 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) {// obtain the proxy catService = ICat for the object of the onBind method of the remote Service. stub. asInterface (service) ;}@ Override public void onServiceDisconnected (ComponentName name) {catService = null ;}}; // 2. bind a remote Service and obtain its content @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); //. obtains the 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 to be bound and set its Action attribute (that is, specify which remote Service to start) Intent intent = new Intent (); intent. setAction ("com. example. service. AIDL_SERVICE "); // c. bindService. BIND_AUTO_CREATE); // d. obtain the remote Service data get through the proxy of the IBinder object. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {try {color. setText (catService. getColor (); weight. setText (catService. getWeight () + "");} catch (RemoteException e) {e. printStackTrace () ;}});} // 3. call this method when exiting the Activity to 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="19" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".AidlClient"            android:label="@string/app_name" >            <intent-filter>                <action android: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 "obtain data from remote Service" button on the program interface to enable the client to read data from the remote 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.