Aidl mechanism for Android interprocess communication (IPC): Hello World Example

Source: Internet
Author: User

The Android implementation IPC can use the AIDL mechanism provided by Android itself. There are many related articles on the Internet, but the writing is too cumbersome and troublesome, the focus is not prominent. This article cobwebs the simplest Android Aidl routine key code from an engineering perspective, explaining how to use Android Aidl in your code in the simplest form.

Aidl is logically divided into "server-side" and "client" in the first place. In this example, it is represented by two completely different, separate eclipse projects.

(1) server. An Android App, the Aidl service provider.

(2) clinet. Another Android App, the Aidl service caller.

The implementation of the demo code functionality is simple:

(1) The service side starts first, after starting, does nothing. When the client process is connected, return to "Hello, world!" String.

(2) Customer connection service side. Get the string returned by the server and print it in Logcat.


Code framework and specific steps:

(1th Step) Create a server-side app in Eclipse. Suppose the name is server. First, create a source code named Serverserviceinterface.aidl on the server and put it in the package. Although the interface definition in Serverserviceinterface.aidl follows the Java specification, the only difference is not to add public, private, and so on. A method of defining a Gethelloworld () in serverserviceinterface.aidl, note that this method is the interface that is subsequently exposed to the client by the server and will be provided to the client, such as:


If there are no write errors in the Serverserviceinterface.aidl source code file, eclipse will automatically generate a Serverserviceinterface.java file in the Gen directory with exactly the same name. There is no need to care about the specifics of Serverserviceinterface.java source code files.


(2nd) Write a class Serverservice.java, inherit from the service, write a Serverserviceinstance.java class inside the Serverservice.java class inherits from SERVERSERVICEINTERFACE.J The stub class in Ava that implements the Gethelloworld () method in this class.


The full source code for Serverservice.java is given below:

Package Zhangphil.aidl.server;import Android.app.service;import Android.content.intent;import android.os.IBinder; public class Serverservice extends Service {public class Serverserviceinstance extends Serverserviceinterface.stub {// This method is for the client to call, returning the client a Hello, world! String. @Overridepublic String Gethelloworld () {return "Hello, World!";}} @Overridepublic ibinder onbind (Intent Intent) {//must return a Serverserviceinstance instance, object for use by the client serverserviceinstance Mserverserviceinstance = new Serverserviceinstance (); return mserverserviceinstance;}}


(3rd) Write a service-side main activity. In this example, to make the code simple, the main activity does not make any excessive aidl-related code, mainactivity only as a "container" to launch the app:

Package Zhangphil.aidl.server;import Android.app.activity;public Class Mainactivity extends Activity {// In order to make the demo code concise short not cumbersome, simply the main activity are commented out. @Override//protected void OnCreate (Bundle savedinstancestate) {//super.oncreate (savedinstancestate);/}}


corresponding Androidmanifest.xml file:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Zhangphil.aidl.server "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <application android:allowbackup=" True "android:icon=" @drawable/ic_launcher "android:label=" @string/app_name "android:theme=" @style/app Theme "> <activity android:name=" zhangphil.aidl.server.MainActivity "android:label=" @st Ring/app_name "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/        > <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <service android:name= "Zhangphil.aidl.server.ServerService" > <intent-f Ilter> <!--action The specific value of the android:name can be given arbitrarily, but it must be guaranteed to be consistent with the client invocation and defined here.                 This style is usually used in shapes such as Action_aidl_server_service or com.xxx.xxx, and so on. --<action android:name= "start_zhangphil_aidl_server_service_action"/> </intent-fi Lter> </service> </application></manifest>


Service-side Androidmanifest.xml Nothing special, the only focus is the need to specify the service written in ' Step (2) ' In this document:

<service android:name= "Zhangphil.aidl.server.ServerService" >            <intent-filter>                <!--action The specific value of the android:name can be given arbitrarily, but it must be guaranteed to be consistent with the client invocation and defined here.                This style is usually used in shapes such as Action_aidl_server_service or com.xxx.xxx, and so on. --                <action android:name= "start_zhangphil_aidl_server_service_action"/>            </ Intent-filter>        </service>

The above is the service side.

Here is the client.


(4th) in Eclipse, create a client app that has the name clients. Copy and paste the automatically generated Serverserviceinterface.java source code files from the Gen directory in the server project project above to the client SRC directory, including the package structure:


(The 5th Step) is basically done here. The next step is to bind the service to the server in the client, and then call the Gethelloworld () method, where the Android serviceconnection is used. Simple period, in the client's mainactivity Bindservice, the serviceconnection in the key method of rewriting, the client mainactivity code:

Package Zhangphil.aidl.client;import Zhangphil.aidl.server.serverserviceinterface;import Android.os.Bundle;import Android.os.ibinder;import Android.util.log;import Android.app.activity;import Android.content.ComponentName; Import Android.content.context;import Android.content.intent;import Android.content.serviceconnection;public class Mainactivity extends Activity {privateserverserviceinterface mserverserviceinterface;private serviceconnection Serviceconnection = new Serviceconnection () {@Overridepublic void onserviceconnected (componentname name, IBinder Service) {mserverserviceinterface = ServerServiceInterface.Stub.asInterface (service); try {String hi= Mserverserviceinterface.gethelloworld (); LOG.D (This.getclass (). GetName (), HI);} catch (Exception e) {e.printstacktrace ();}} @Overridepublic void onservicedisconnected (componentname name) {}} @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate);//The value of the constructed intent must be the same as the value defined by the invoked service-side. In this case, the server-side androidmanifThe Action Namebindservice (new Intent ("Start_zhangphil_aidl_server_service_action") that defines the service in Est.xml, Serviceconnection, context.bind_auto_create); }}

There are two key points in the 5th step:

(1) construct serviceconnection, override Onserviceconnected () method in Serviceconnection. If the client connects to the service-side process successfully, then onserviceconnected () will be recalled.

(2) Call Bindservice () to initiate a connection to the service process side.


When the above is complete, start the server first, and then start the Logcat output on the client,client side:

One of the simplest Android IPC Aidl's Hello World finishes!




Aidl mechanism for Android interprocess communication (IPC): Hello World Example

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.