Communication between IPC processes in Android development-AIDL introduction and instance analysis

Source: Internet
Author: User

Communication between IPC processes in Android development-AIDL introduction and instance analysis
I. IPC inter-process communication IPC is a general term for inter-process communication methods. Linux IPC includes the following methods. What are the main methods used for inter-process communication in Android? 1. pipeline (Pipe) and famous Pipeline (named pipe): pipeline can be used for communications between kinship processes. Famous pipelines overcome the Pipe's no-name restrictions. Therefore, in addition to the functions of pipelines, it also allows communication between unrelated processes; 2. signal: a Signal is a complex communication method used to notify the receiving process of an event. In addition to inter-process communication, the process can also send a Signal to the process itself; in addition to the early Unix signal semantic function sigal, linux also supports the signal function sigaction whose semantics complies with the Posix.1 standard (in fact, this function is based on BSD, BSD in order to achieve reliable signal mechanism, it can also unify external interfaces and implement the signal function again using the sigaction function); 3. message Queue: A chain table of messages, including the Posix Message Queue system V Message queue. A process with sufficient permissions can add messages to the queue. A process with the read permission can read messages from the queue. The message queue overcomes the disadvantages of low signal carrying information, and the pipeline can only carry unformatted byte streams and limited buffer size. 4. Shared Memory: Enables multiple processes to access the same memory space. It is the fastest available IPC format. It is designed to reduce the running efficiency 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. semaphores (semaphore): used for synchronization between processes and between different threads of the same process. 6. Socket: a more general inter-process communication mechanism, which can be used for inter-process communication between different machines. It was initially developed by the BSD branch of the Unix System, but now it can be transplanted to other Unix-like systems: both Linux and System V variants support sockets. Ii. AIDL (Android Interface Definition Language) AIDL-Android Interface Definition Language. In Android, applications run in independent processes. Applications cannot access each other's memory space. Sometimes the PCI mechanism is used to implement inter-process communication. Android supports the PCI mechanism, but Android needs to understand the serialized data (serialized aling/un stored aling of data). AIDL is generated to describe such data. It is an interface definition language. The syntax is similar to that of JAVA. aidl, which is written in the file and published to the client interface declaration. In this article, we will integrate the two segments into an android project to learn from the experience of the client and two android projects on the server side, which may be clearer. Let's take a look at instance resolution. Iii. introduction and analysis of AIDL 1. AIDL introduces that in Android, each Application is executed in its own process and cannot be directly called to other Application resources. This is also in line with the concept of "sandbox. The so-called sandbox principle is generally used in mobile phone businesses to isolate applications in part or whole. We will not introduce sandbox technology much here. Therefore, in Android, some operations are restricted when an application is executed, such as memory access, sensor access, and so on. In this way, the system can be protected to the maximum extent, so that applications do not "do what they want ". What should we do if we sometimes need to interact between applications? Therefore, Android needs to implement the IPC protocol. However, this protocol is still a bit complex, mainly because the data management system (data transmission between processes or threads) needs to be implemented ). Android implements our own IPC, that is, AIDL. 2. Defining the AIDL interface AIDL is a lightweight Implementation of IPC, using a syntax that is familiar to Java developers. Android also provides a tool to automatically create Stub (class architecture and class skeleton ). When we need to communicate between applications, we need to take the following steps:. define an AIDL interface B. implement Stub c. expose the service to the customer program. the syntax for instance parsing AIDL is similar to that of Java interfaces. You only need to define the method signature. The data types supported by AIDL are somewhat different from those supported by Java interfaces. all basic types (int, char, etc.) B. string, List, Map, CharSequence, and other Class c. other AIDL interface TYPES d. all Parcelable classes are parsed using a calculator as an example. (1) create a project and create an AIDL interface: create a file named IAdditionService. aidl can 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 in the gen/com/android/hellosumaidl folder. java file. Because it is automatically generated, no changes are required. This file contains Stub, which we will implement for our remote service. (2) To implement remote services, we first create a class named AdditionService. java. In order to implement our services, we need to let the onBind method in this class return an IBinder class object. The IBinder class object represents the implementation of the remote service. To implement this service, we need to use the automatically generated subclass IAdditionService. Stub. We must also implement the add () function defined in the AIDL file. The following is the remote Service code: copy the code public class AdditionService extends Service {@ Override public void onCreate () {super. onCreate () ;}@ Override public IBinder onBind (Intent intent) {// TODO Auto-generated method stub return new IAdditionService. stub () {@ Override public int add (int value1, int value2) throws RemoteException {// TODO Auto-generated method stub return value1 + value2 ;};}@ Override public void OnDestroy () {super. onDestroy () ;}} copy the code (3) to provide the service ("expose" the service to the user). Once the onBind method in the service is implemented, we can put the Client Program (here is MainActivity. java) is connected to the service. To establish such a link, we need to implement the ServiceConnection class. We create an internal class AdditionServiceConnection in MainActivity. java, which inherits the ServiceConnection class and overwrites the two methods: onServiceConnected and onServiceDisconnected. The code for the internal class is as follows: copy the code class AdditionServiceConnection implements ServiceConnection {@ Override public void onServiceConnected (ComponentName, IBinder boundService) {// TODO Auto-generated method stub service = IAdditionService. stub. asInterface (IBinder) boundService); Toast. makeText (MainActivity. this, "Service connected", Toast. LENGTH_SHORT ). show () ;}@ Override public void onServiceDisconnected (ComponentName name) {// TODO Auto-generated method stub service = null; Toast. makeText (MainActivity. this, "Service disconnected", Toast. LENGTH_SHORT ). show () ;}copy code (4) related code and effect MainActivity. the full java code is as follows: copy the code package com. czm. hellosumaidl; import android. app. activity; import android. content. componentName; import android. content. context; 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; import android. widget. textView; import android. widget. toast; public class MainActivity extends Activity {IAdditionService service; AdditionServiceConnection connection; EditText value1; EditText value2; TextView result; Button buttonCalc; @ Override protected void onCreate (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 (new OnClickListener () {@ Override public void onClick (View v) {int v1, 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 () ;}}) ;}@ Override protected void onDestroy () {super. onDestroy (); releaseService ();}/** This function connects the Activity to the service */private void initService () {connection = new AdditionServiceConnection (); intent I = new Intent (); I. setClassName ("com. czm. hellosumaidl ", com. czm. hellosumaidl. additionService. class. getName (); boolean ret = this. bindService (I, connection, Context. BIND_AUTO_CREATE);}/** This function disconnects the Activity from the service */private void releaseService () {unbindService (connection); connection = null ;} class AdditionServiceConnection implements ServiceConnection {@ Override public void onServiceConnected (ComponentName, IBinder boundService) {// TODO Auto-generated method stub service = IAdditionService. stub. asInterface (IBinder) boundService); Toast. makeText (MainActivity. this, "Service connected", Toast. LENGTH_SHORT ). show () ;}@ Override public void onServiceDisconnected (ComponentName name) {// TODO Auto-generated method stub service = null; Toast. makeText (MainActivity. this, "Service disconnected", Toast. LENGTH_SHORT ). show ();}}}

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.