Inter-process communication --- AIDL use instance, --- aidl instance

Source: Internet
Author: User

Inter-process communication --- AIDL use instance, --- aidl instance
AIDL (Android Interface Definition Language) is an IDL Language used to generate code for interprocess communication (IPC) between two processes on the Android device. If you want to call operations on objects in another process (such as Service) in a process (such as Activity), you can use AIDL to generate serializable parameters. This article briefly introduces the use of AIDL.

1. Create IRemoteService. aidl

package com.tang.remoteservicedemo;interface IRemoteService { String getInfo();}
It can be seen from the content that this is similar to an interface. Since such a thing is defined, we need to implement it.

2. Create an IService "Implementation" IRemoteService "interface"

Package com. tang. remoteservicedemo; import java. util. date; import android. app. service; import android. content. intent; import android. OS. IBinder; import android. OS. remoteException; public class IService extends Service {private IBinder iBinder = new IRemoteService. stub () {@ Overridepublic String getInfo () throws RemoteException {// TODO Auto-generated method stubreturn new Date (System. currentTimeMillis ()). t OLocaleString () + "remote service information! ";}};@ Overridepublic IBinder onBind (Intent intent) {// TODO Auto-generated method stubreturn iBinder ;}}
Communication between different processes based on Binder. The Client and Service are in different processes. For user programs, when the IBinder interface returned by the Service is called, the method for accessing the Service is the same as calling your own function.

3. Configure IService for other processes to call

        <service android:name="com.tang.remoteservicedemo.IService"            android:process=":remote">            <intent-filter>                <action android:name="com.tang.remoteservicedemo.IService"/>            </intent-filter>        </service>

Configure a process name and an action.

Through the preceding three steps, the service containing the getInfo () method can be called by someone else.

4. Create a ClientDemo project and copy all the packages containing IRemoteService. aidl to src, leaving only the aidl file and deleting all the other packages.


5. Create a MainActivity. The other is the service binding operation.

package com.tang.clientdemo;import java.util.Timer;import java.util.TimerTask;import com.tang.remoteservicedemo.IRemoteService;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.util.Log;public class MainActivity extends Activity {private IRemoteService iService = null;private boolean isBinded =false;ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stubisBinded = false;iService = null;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubiService = IRemoteService.Stub.asInterface(service);isBinded = true;}};public void doBind() {    Intent intent = new Intent("com.tang.remoteservicedemo.IService");    bindService(intent, conn, Context.BIND_AUTO_CREATE);}public void doUnbind() {    if (isBinded)     {      unbindService(conn);      iService = null;      isBinded = false;    }}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubdoBind();}}).start();Timer timer = new Timer();timer.schedule(task, 0, 2000);}TimerTask task = new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubif(iService!=null){try {Log.i("AAA", iService.getInfo());} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();}}else{Log.i("AAA", "iService!=null");}}};@Overrideprotected void onDestroy() {// TODO Auto-generated method stubdoUnbind();task.cancel();super.onDestroy();}}

The executed Log is as follows:

Why is there an empty Log? It takes time to bind the Log ....

There are so many simple AIDL applications.

Source code download


Help me write a C # example: communication between two processes

// Client:

Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Text;
Using System. Windows. Forms;
// Add namespace reference
Using System. Net;
Using System. Net. Sockets;
Using System. Threading;
Using System. IO;

Namespace ChatClient
{
Public partial class FormClient: Form
{
Private bool isExit = false;
Private delegate void SetListBoxCallback (string str );
Private SetListBoxCallback setListBoxCallback;
Private TcpClient client;
Private NetworkStream networkStream;
Private BinaryReader br;
Private BinaryWriter bw;
Public FormClient ()
{
InitializeComponent ();
ListBoxStatus. HorizontalScrollbar = true;
SetListBoxCallback = new SetListBoxCallback (SetListBox );
}
Private void buttonConnect_Click (object sender, EventArgs e)
{
Try
{
// Change Dns. GetHostName () to the server domain name in actual use.
Client = new TcpClient (Dns. GetHostName (), 51888 );
SetListBox (string. Format ("Local EndPoint: {0}", client. Client. LocalEndPoint ));
SetListBox ("Connection established with server successful ");
}
Catch
{
SetListBox ("failed to connect to server ");
Return;
}
ButtonConnect. Enabled = false;
// Obtain the network stream
NetworkStream = client. GetStrea... the remaining full text>

How can I use AIDL to design remote interfaces in Android?

On the Android platform, a process generally cannot access the memory space of another process. Therefore, to perform a conversation, you need to break down the object into basic units that the operating system can understand and orderly pass through the process boundary.
It is tedious to implement this data transmission process through code. Android provides the AIDL tool to handle this task. AIDL (AndroidInterfaceDefinitionLanguage) is an IDL Language used to generate code for inter-process communication (IPC) between two processes on the Android device. If you want to call operations on objects in another process (such as Service) in a process (such as Activity), you can use AIDL to generate serializable parameters. The AIDLIPC mechanism is interface-oriented, like COM or Corba, but more lightweight. It uses a proxy class to transmit data on the client and the implementation end.
1. Use AIDL to implement IPC (ImplementingIPCUsingAIDL)
To use AIDL to implement the IPC service, follow these steps: 1. Create the. aidl file. This file (YourInterface. aidl) defines available client methods and data interfaces. Second, add the. aidl file to the makefile file (the ADT plug-in Eclipse provides the management function ). Android includes a compiler named AIDL, which is located in the tools/folder. Third, the implementation interface-The AIDL compiler uses the Java language to create interfaces from the AIDL interface file. This interface has an inherited internal abstract class named Stub (some additional methods for calling IPC have been implemented). You must create an internal abstract class that inherits from YourInterface. stub class, and implemented in. methods declared in the aidl file. Fourth, open interfaces to the client. If you are writing a Service, you should inherit the Service and reload Service. onBind (Intent) to return the object instance that implements the interface.
2. Create a. aidl file (Createan. aidlFile)
AIDL uses a simple syntax to declare an interface and describe the parameters and return values of its methods and methods. These parameters and return values can be of any type, or even interfaces generated by other AIDL. Note that all non-built-in types must be imported. AIDL supports the following types of data: first, the main types of Java programming language (int, boolean, etc.) do not require the import Statement. Second, the import Statement declaration is required for the APIS generated by other AIDL passed in reference mode. Third, to implement Parcelableprotocol and custom classes passed by value, you must declare the import statement. In addition, there are some import statements not required, such as String.
3. ImplementingtheInterface)
AIDL and. if you use the Eclipse plug-in, aidl runs automatically as part of the compilation process (you do not need to run AIDL before compiling the Project). If there is no plug-in, you need to run AIDL first.
The generated interface contains an abstract internal class named Stub, which declares all. the methods described in aidl, Stub also defines a small number of auxiliary methods, especially asInterface (), through which IBinder (when applicationContext. when bindService () is successfully called, it is passed to the onServiceConnected () of the client and an interface instance used to call the IPC method is returned. To implement your own interface, start with YourInterface. stub class inheritance, and then implement the relevant methods (you can create. aidl files implement the stub method instead of intermediate compilation. The Android compilation process is. java file processing. aidl file ).
After implementing the interface, you need to expose the interface to the client, that is, publish the service. The implementation method is to inherit the Service, and then implement

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.