Android Interface Definition Language (AIDL)

Source: Internet
Author: User

Android Interface Definition Language (AIDL)
IN THIS DOCUMENT
Defining an AIDL Interface
Create the. aidl file
Implement the interface
Expose the interface to clients
Passing Objects over IPC
Calling an IPC Method
SEE ALSO
Bound Services
AIDL (Android Interface Definition Language) is similar to other Interface Definition languages. Define this interface. The client and service can communicate with each other through this interface. Therefore, to transfer an object between processes, you need to break down the object into commands that the system can recognize. It is very tedious to implement it through code. The android system can process it through AIDL.

Note: AIDL is used only when the service needs to be accessed from different applications and multi-thread processing is required for the service. If you do not need to process IPC from other applications, You can implement Binder. If you need IPC but do not need to process multithreading, you can use Messenger. Before using it, consider which method is suitable for you.

Before designing the AIDL interface, you must confirm the methods in the AIDL interface. It cannot be assumed that thread will accompany when a call occurs. What happens is different, depending on the call initiated from the local process or remote process thread. Specifically:


The same thread in the local process initiates a call request. If this is your main UI thread, the thread continues to be executed on the AIDL interface. If it is another thread, it will run code in the service. If only a local thread accesses the service, it can control the execution of specific threads in the service. (If AIDL is not required in this case, it can be replaced by the Binder method ).
Initiate a call from the thread pool of the remote process. Prepare the call initiated when the unknown thread is processed. In other words, AIDL must ensure the security of all threads.
The oneway keyword modifies the behavior of remote CILS. when used, a remote call does not block; it simply sends the transaction data and immediately returns. the implementation of the interface eventually generated es this as a regular call from the Binder thread pool as a normal remote call. if oneway is used with a local call, there is no impact and the call is still synchronous.
Defining an AIDL Interface

--------------------------------------------------------------------------------

You can use the syntax of Java programming language to define the AIDL interface. files are stored in the source code (src/). The current application owns this service and other applications can bind this service.

When the constructed application contains the. aidl file, the Android SDK can generate an IBinder Interface Based on the. aidl file and save it to the project's gen/directory. The service should reasonably implement the IBinder interface. The client application can bind this service and call the service method through IBinder.

To create a bound service with AIDL, follow these steps:

Create a. aidl File
This file defines interfaces and methods.

Implementation Interface
The Android SDK can generate an interface based on the. aidl file. The Interface contains an abstract internal class named Stub and implements the methods defined in the AIDL interface. When using it, you must inherit the Stub class and implement its method.

Public interface
Implement service and override onBind (). Its return value is stub class.

Caution: any changes made to the AIDL interface must be backward compatible to prevent other applications that use the service from continuing to work. That is to say, because the. aidl file must be copied to other applications, in order to access the service interface, the original interface must be supported.

1. Create a. aidl File
AIDL uses a simple syntax to define an interface. There can be one or more methods that can be passed in parameters and return values. Parameters and return values can be any type, or even APIs generated by aidl.

The. aidl file must use the java syntax. Each. aidl file can only define a separate interface, and only the interface declaration and method declaration are required.

Generally, AIDL supports the following data types:

All basic java types (such as int, long, char, boolean, etc)
String
CharSequence
List
All the elements in the List must be of the type supported by AIDL, or other AIDL interfaces and defined parcebles. A List can be used as a common class (for example, List <String> ). the actual class is always an ArrayList, although this method is used to generate the List interface.

Map
All the elements in Map must be of the type supported by AIDL, or other AIDL interfaces and defined parcebles. usually Map (for example, Map in the form of Map <String, Integer> is not supported ). The actual class is always a HashMap, although the method is generated by the Map interface.

When the type to be imported is not listed above, import is required, even if they are defined in the same package as the current AIDL file.

When defining the service interface, you must be aware of the following:

The method can have 0 or more parameters, and can return a value or void.
All non-primitive parameters require a directional tag indicating which way the data goes. Either in, out, orinout (see the example below ).
Primitives are in by default, and cannot be otherwise.

Caution: you must consider the data direction you actually need, because data loading and replacement are very expensive.

All annotations contained in. aidl are generated in the IBinder interface (except the annotations before import and package)
Only methods are supported, but static member variables are not supported.
The following is an example of the. aidl file:

// IRemoteService. aidl
Package com. example. android;

// Declare any non-default types here with import statements

/** Example service interface */
Interface IRemoteService {
/** Request the process ID of this service, to do edevil things with it .*/
Int getPid ();

/** Demonstrates some basic types that you can use as parameters
* And return values in AIDL.
*/
Void basicTypes (int anInt, long aLong, boolean sort lean, float aFloat,
Double aDouble, String aString );
} Save the. aidl file in the src/directory. when compiling the project, SDK tools generates the IBinder interface file and stores it in the project's gen/directory.

If you are using Eclipse, the Binder class will be generated quickly. If you do not use Eclipse, Ant tool can automatically generate the binder class next time you build the application-ant debug (or ant release) is required when you build the project. the aidl file is constructed once so that the generated class can be referenced during encoding.

2. Implementation Interface
When you build a project, the Android SDK generates a java interface file. The generated interface file contains an internal abstract class of Stub, which is defined in. aidl.

Note: Stub also defines some helper group methods, especially asInterface (), which requires an IBinder (onServiceConnected () callback method that is usually passed to the customer ), and return an instance of the stub interface. See the section Calling an IPC Method for more details on how to make this cast.

To implement the interface generated from the. aidl file, inherit the generated Binder interface (for example, YourInterface. Stub) and implement the method inherited from the. aidl file.

Here is an example of implementing the IRemoteService interface through an anonymous class:

Private final IRemoteService. Stub mBinder = new IRemoteService. Stub (){
Public int getPid (){
Return Process. myPid ();
}
Public void basicTypes (int anInt, long aLong, boolean sort lean,
Float aFloat, double aDouble, String aString ){
// Does nothing
}
}; Now, mBinder is an instance of the Stub class. In the next step, this interface needs to be exposed to the client for calling.

Here are some rules for implementing the AIDL interface:

It cannot be guaranteed that a call is initiated from the main thread. Therefore, you must consider multi-threaded startup and ensure thread security during service running.
By default, remote calls are synchronized. If you know that the task completed by your service takes some time and you cannot call the service from the main thread of the activity, this call will cause the application to be suspended (the application waits for a response ), it is best to call it in a new thread.
The Service does not return any exceptions thrown by the developer to the caller.
3. Publish the interface to the client
Once the service implements the interface, it must be exposed to the client so that the client can bind it. Exposes an interface for the service, inherits the Service and implements onBind (), and returns an instance implementing the Stub class. The following service example discloses the IRemoteService interface to clients.

Public class RemoteService extends Service {
@ Override
Public void onCreate (){
Super. onCreate ();
}

@ Override
Public IBinder onBind (Intent intent ){
// Return the interface
Return mBinder;
}

Private final IRemoteService. Stub mBinder = new IRemoteService. Stub (){
Public int getPid (){
Return Process. myPid ();
}
Public void basicTypes (int anInt, long aLong, boolean sort lean,
Float aFloat, double aDouble, String aString ){
// Does nothing
}
};
} Now, when the client calls bindService () to bind the service, the Client uses the onServiceConnected () callback function to obtain the mBinder instance of the service onBind () method.

The client can access the interface class. If the client and service are in different applications, the client application must copy the. aidl file to its own src/directory. (Generate the android. OS. Binder interface-provide the AIDL Method to the client ).

When the client obtains the IBinder object from onServiceConnected (), it needs to call YourServiceInterface. Stub. asInterface (service) and convert the returned parameters to its own ServiceInterface. For example:

IRemoteService mIRemoteService;
Private ServiceConnection mConnection = new ServiceConnection (){
// Called when the connection with the service is established
Public void onServiceConnected (ComponentName className, IBinder service ){
// Following the example abve for an AIDL interface,
// This gets an instance of the IRemoteInterface, which we can use to call on the service
MIRemoteService = IRemoteService. Stub. asInterface (service );
}

// Called when the connection with the service disconnects unexpectedly
Public void onServiceDisconnected (ComponentName className ){
Log. e (TAG, "Service has unexpectedly disconnected ");
MIRemoteService = null;
}
};

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.