-aidl Introduction and example analysis of IPC interprocess communication between Android development

Source: Internet
Author: User
Tags gettext

I. Communication between IPC processes

IPC is an inter-process communication method, the Linux IPC includes the following methods, what is the main use of Android interprocess communication methods?

1. Piping (pipe) and famous pipes (named pipe): Pipelines can be used for communication between affinity processes, and well-known pipelines overcome the limitations of pipe without name, so that, in addition to having the functions of a pipe, it allows communication between unrelated processes;
2. Signal (Signal): signal is a more complex mode of communication, used to inform the receiving process of an event occurred, in addition to inter-process communication, the process can also send signals to the process itself; Linux in addition to supporting the UNIX early signal semantic function Sigal outside, Also support the semantics of the POSIX.1 standard signal function sigaction (in fact, the function is based on BSD, BSD in order to achieve a reliable signal mechanism, but also able to unify the external interface, with sigaction function to re-implement the signal function);
3. Message queue (Message Queuing): Messages queue is a linked table of messages, including POSIX Message Queuing system V Message Queuing. A process with sufficient permissions can add messages to the queue, and a process that is given Read permission can read the messages in the queue. Message queue overcomes the disadvantage that the signal carrying information is low, the pipeline can only carry the unformatted byte stream and the buffer size is limited.
4. Shared memory: Allows multiple processes to access the same piece of memory space, is the fastest available IPC form. is designed for inefficient operation of other communication mechanisms. It is often used in conjunction with other communication mechanisms, such as semaphores, to achieve synchronization and mutual exclusion between processes.
5. Semaphore (semaphore): primarily as a means of synchronization between processes and between different threads of the same process.
6. Socket (socket): More general inter-process communication mechanism, can be used for inter-process communication between different machines. Originally developed by the BSD branch of the UNIX system, it can now be ported to other Unix-like systems: both Linux and System V variants support sockets.

Second, aidl (Android Interface Definition Language)

Aidl-android Interface Definition Language-android Interface Definition language. Because in Android, the application runs in its own separate process. There is no access to the other's memory space between applications. Sometimes the PCI mechanism is used to achieve inter-process communication.    Android supports the PCI mechanism, but requires Android to read the serialized data (Marshaling/un marshaling by). Aidl is designed to describe such data, which is an interface definition language. The syntax is similar to the Java,.aidl file that is advertised to the client interface declaration.

In this article, in order to draw on the client, server-side two Android project experience, the two-segment integration into an Android project, this may be more clear. Let's take a look at example parsing.

Three, Aidl introduction and analysis

1.AIDL Introduction

In Android, each application (application) executes in its own process and cannot directly invoke resources to other applications, which also conforms to the "sandbox" concept. The so-called sandbox principle, generally used in mobile phone business, is simply designed to isolate applications partially or completely. About Sandbox technology we don't introduce much here. So, in Android, when an app is executed, some actions are limited, such as accessing memory, accessing sensors, and so on. Doing so maximizes the protection of the system, lest the application "do whatever it wants". So how do we sometimes need to interact between apps? As a result, Android needs to implement the IPC protocol. However, this protocol is a bit more complex, primarily because of the need to implement a data management system (passing data between processes or threads). Android has implemented its own IPC, also known as Aidl.

2. Defining the Aidl interface

Aidl is a lightweight implementation of the IPC, with a familiar syntax for Java developers. Android also provides a tool that can automatically create stubs (class schemas, class skeletons). When we need to communicate between applications, we need to follow these steps:

A. Defining a AIDL interface

B. Implementing stubs for Remote services (service)

C. Use of the service "exposed" to the client program

3. Example parsing

The syntax of AIDL is similar to the Java Interface (Interface), and only the signature of the method needs to be defined.

Aidl supported data types are somewhat different from the data types supported by the Java interface

A. All underlying types (int, char, etc.)

B. String,list,map,charsequence and other categories

C. Other Aidl interface types

D. All classes of parcelable

The following is an example of an adder to parse.

(1) Create a project, create a AIDL interface: New file, named Iadditionservice.aidl

 Package Com.czm.hellosumaidl; Interface iadditionservice{    int Add (int value1,int  value2);}

Once the file is saved, the Android Aidl tool automatically generates the corresponding Iadditionservice.java file in the gen/com/android/hellosumaidl folder. Because it is generated automatically, there is no need to change it. The stub is included in this file, and we will then implement this stub for our remote service.

(2) Realize remote service

First we create a new class, named Additionservice.java . To implement our service, we need to let the onbind method in this class return an object of the IBinder class. The object of this IBinder class represents the implementation of the remote service. In order to implement this service, we need to use the auto-generated subclass Iadditionservice.stub . In this, we must also implement the Add () function that we have previously defined in the Aidl file. Here is the code for our remote service:

 Public classAdditionserviceextendsservice{@Override Public voidonCreate () {Super. OnCreate (); } @Override Publicibinder onbind (Intent Intent) {//TODO auto-generated Method Stub        return Newiadditionservice.stub () {@Override Public intAddintValue1,intvalue2)throwsRemoteException {//TODO auto-generated Method Stub                returnValue1 +value2;    }        }; } @Override Public voidOnDestroy () {Super. OnDestroy (); } }

(3) Provision of services ("exposure" service to users)

Once the Onbind method in the service is implemented, we can connect the client program (here is Mainactivity.java ) with the service. In order to create such a link, we need to implement the Serviceconnection class. We create an inner class additionserviceconnection in Mainactivity.java , which inherits the Serviceconnection class, and rewritten its two methods: onserviceconnected and onservicedisconnected. The code for the inner class is given below:

classAdditionserviceconnectionImplementsserviceconnection {@Override Public voidonserviceconnected (componentname name, IBinder boundservice) {//TODO auto-generated Method StubService =IAdditionService.Stub.asInterface ((ibinder) boundservice); Toast.maketext (mainactivity. This, "Service Connected", Toast.length_short). Show (); } @Override Public voidonservicedisconnected (componentname name) {//TODO auto-generated Method StubService =NULL; Toast.maketext (mainactivity. This, "Service Disconnected", Toast.length_short). Show (); }    }

(4) Related codes and effects

The full code for Mainactivity.java is as follows:

 PackageCom.czm.hellosumaidl;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.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {Iadditionservice service;    Additionserviceconnection connection;    EditText value1;    EditText value2;    TextView result;    Button Buttoncalc; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main);        Initservice (); Buttoncalc=(Button) Findviewbyid (R.ID.BUTTONCALC); Value1=(EditText) Findviewbyid (r.id.value1); Value1.settext ("23"); value2=(EditText) Findviewbyid (r.id.value2); Value2.settext ("24"); Result=(TextView) Findviewbyid (R.id.result); Buttoncalc.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {intV1, v2, res =-1; V1=Integer.parseint (Value1.gettext (). toString ()); V2=Integer.parseint (Value2.gettext (). toString ()); Try{res=Service.add (v1, v2); } Catch(RemoteException e) {e.printstacktrace ();            } result.settext (Integer.valueof (res). toString ());    }        }); } @Overrideprotected voidOnDestroy () {Super. OnDestroy ();    Releaseservice (); }    /** This function connects the Activity to the service*/    Private voidInitservice () {connection=Newadditionserviceconnection (); Intent I=NewIntent (); I.setclassname ("Com.czm.hellosumaidl", Com.czm.hellosumaidl.AdditionService.class. GetName ()); BooleanRET = This. Bindservice (i, connection, context.bind_auto_create); }    /** This function disconnects the Activity from the service*/    Private voidReleaseservice () {unbindservice (connection); Connection=NULL; }    classAdditionserviceconnectionImplementsserviceconnection {@Override Public voidonserviceconnected (componentname name, IBinder boundservice) {//TODO auto-generated Method StubService =IAdditionService.Stub.asInterface ((ibinder) boundservice); Toast.maketext (mainactivity. This, "Service Connected", Toast.length_short). Show (); } @Override Public voidonservicedisconnected (componentname name) {//TODO auto-generated Method StubService =NULL; Toast.maketext (mainactivity. This, "Service Disconnected", Toast.length_short). Show (); }    }}

The effect is as follows:

                                    Execute Aidl interface before                                                        ,         &N Bsp                                  &NBS p; After executing the Aidl interface

Related Article

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.