Thoroughly understand AIDL in Android and Its Usage

Source: Internet
Author: User

1. Why AIDL? No matter what you learn, you must first understand why you want to have it. Do not say that existence is reasonable. It must be reasonable, but you still do not understand it. The simple concept of AIDL is that AIDL can access other applications and communicate with other applications across processes. I will tell you that many technologies are accessible, for example, broadcast (application A is in AndroidManifest. register the broadcast of the specified Action in xml.) application B sends the broadcast of the specified Action, so that A can receive the information. This can also be seen as communication between different applications (but this communication is unidirectional ); for example, ContentProvider exposes data to other applications through the URI interface, but such data is not counted as communication between applications. Perhaps the most confusing thing is the Messager launched by Android, which completes communications between applications. So why AIDL? The official document introduces the following sentence in AIDL:

Note: Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service. If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger. Regardless, be sure that you understand Bound Services before implementing an AIDL.
The first sentence is the most important. "You must use AIDL only when you allow different clients to access your service and need to handle multithreading issues ", in other cases, you can select other methods, such as Messager, and cross-process communication. It can be seen that AIDL Handles multi-thread and multi-client concurrent access. Messager is a single thread. The official document explains why AIDL is required in one sentence. If so, try writing AIDL. 2. Use AIDL. 1. Define the AIDL file.
// IRemoteService.aidlpackage 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 evil 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 aBoolean, float aFloat,            double aDouble, String aString);}
This code is also officially documented. Name it IRemoteService. aidl, put in com. example. android package (this can be used at Will). After saving, the Android compiler will automatically generate IRemoteService under the gen directory. java file 2. Define our service, DDService. java, and must be in AndroidManifest. add "duanqing. test. aidl "ACTION
package com.example.service;import com.example.android.IRemoteService;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.Process;public class DDService extends Service {@Overridepublic void onCreate() {super.onCreate();System.out.println("DDService onCreate........" + "Thread: " + Thread.currentThread().getName());}@Overridepublic IBinder onBind(Intent arg0) {System.out.println("DDService onBind");return mBinder;}private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {    public int getPid(){    System.out.println("Thread: " + Thread.currentThread().getName());    System.out.println("DDService getPid ");        return Process.myPid();    }    public void basicTypes(int anInt, long aLong, boolean aBoolean,        float aFloat, double aDouble, String aString) {    System.out.println("Thread: " + Thread.currentThread().getName());    System.out.println("basicTypes aDouble: " + aDouble +" anInt: " + anInt+" aBoolean " + aBoolean+" aString " + aString);    }};}

In this way, our server is complete. We can run the server on the simulator (or on the mobile phone) and wait for a moment to see the printed information, focusing on the "thread name"
Third, to implement the client test code to create another project, you also need to add the AIDL protocol file (this is a standard protocol file that defines external services). Here I will list my test code:
Package com. example. aidlclient; 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. process; import android. OS. remoteException; import android. view. view; import com. example. android. IRemoteService; public class MainActivity Extends Activity {private IRemoteService remoteService; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main);} ServiceConnection conn = new ServiceConnection () {@ Overridepublic void onServiceDisconnected (ComponentName name) {}@ Overridepublic void onServiceConnected (ComponentName, IBinder service) {remoteServic E = IRemoteService. stub. asInterface (service); try {int pid = remoteService. getPid (); int currentPid = Process. myPid (); System. out. println ("currentPID:" + currentPid + "remotePID:" + pid); remoteService. basicTypes (12,122 3, true, 12.2f, 12.3, "Our love, I understand");} catch (RemoteException e) {e. printStackTrace ();} System. out. println ("bind success! "+ RemoteService. toString () ;}};/click * @ param view */public void buttonClick (View view) {System. out. println ("begin bindService"); Intent intent = new Intent ("duanqing. test. aidl "); bindService (intent, conn, Context. BIND_AUTO_CREATE) ;}@ Override protected void onDestroy () {super. onDestroy (); unbindService (conn );}}
4. Execute and click the client button to execute and view the print information:
Check the server print, DDService onCreate .......... thread: main, main Thread. When the client calls the getPid method of the server, the server executes the method in Thread: Binder2. When the client calls the basicType method of the server, the server executes the method in Thread: Binder1.

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.