Basic Android skills: Cross-process Services (AIDL Service)

Source: Internet
Author: User

I. Introduction to AIDL Service

In the Android system, each application runs in its own process, and processes cannot communicate directly. To implement interprocess communication (IPC), Android provides the AIDL Service;

2. Different from the local Service

  • Local Service: The second parameter of the onServiceConnected method of ServiceConnection of the client directly passing the IBinder object itself;

  • Remote Service: the second parameter of the onServiceConnected method of ServiceConnection of the client is sent to only the proxy of the IBinder object;

    Iii. AIDL File

    Android requires the Android Interface Definition Language (AIDL) to define remote interfaces. This Interface Definition Language is not actually a Language, but a communication Interface between two processes;

    Similar to Java interfaces, but there are the following differences:

    • The source code of the AIDL-defined interface must end with. aidl;

    • The data types used by AIDL, except for the basic types, String, List, Map, and CharSequence, all other types need to be imported, even if they need to be imported in the same package;

      4. Steps for using AIDL (the detailed code can be found in the AIDLService and AIDLClient projects)

      1. Create an AIDL File

      package com.example.aidlservice;  interface ICat {     String getColor();     double getWeight(); } 
      After the AIDL file is defined, the ADT tool will automatically generate an ICat in the gen/com/example/aidlservice/directory. java interface, which contains a Stub internal class and implements the IBinder and ICat interfaces. This Stub class will be used as a remote Service callback class;

      2. Expose the interface to the client

      Package com. example. aidlservice; import java. util. timer; import java. util. timerTask; import com. example. aidlservice. ICat. stub; import android. app. service; import android. content. intent; import android. OS. IBinder; import android. OS. remoteException; public class AidlService extends Service {String [] colors = new String [] {"red", "yellow", "black "}; double [] weights = new double [] {2.3, 3.1, 1.58}; private String color; private double weight; private CatBinder catBinder; Timer timer = new Timer (); @ Override public void onCreate () {super. onCreate (); catBinder = new CatBinder (); timer. schedule (new TimerTask () {@ Override public void run () {// randomly change the color in the service component. The value of weight attribute int rand = (int) (Math. random () * 3); color = colors [rand]; weight = weights [rand]; System. out. println ("---------" + rand) ;}}, 0,800) }; @ Override public IBinder onBind (Intent arg0) {/*** return the CatBinder object, when binding a local Service, * This catBinder will directly pass the second parameter of the ServiceConnected * () method of the ServiceConnected object of the client; when binding a remote Service *, only send the proxy of the catBinder object to the second parameter */return catBinder;} @ Override public void onDestroy () {timer of the ServiceConnected () method of the client's ServiceConnected object. cancel ();}/*** inherits Stub, that is, the ICat interface is implemented, and implemented the IBinder interface ** @ author pengcx **/public class CatBinder extends Stub {@ Override public String getColor () throws RemoteException {return color;} @ Override public double getWeight () throws RemoteException {return weight ;}}}

      Configure the Service in the AndroidManifext. xml file;

                
                          
              
            

      3. Client Access to AIDLService

      Copy the AIDL file of the Service to the client. Note that the AIDL file must be under the same package name.

      Package com. example. aidlclient; import com. example. aidlservice. ICat; 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. app. activity; import android. app. service; import android. content. componentName; import android. content. intent; import android. content. serviceConnection; public class AidlClient extends Activity {private ICat catService; private Button getButton; private EditText colorEditText, weightEditText; private ServiceConnection conn = new ServiceConnection () {@ Override public void onServiceDisconnected (ComponentName) {catService = null ;}@ Override public void onServiceConnected (ComponentName, IBinder service) {// obtain the object proxy catService = ICat returned by the onBinder method of the remote Service. stub. asInterface (service) ;}}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_aidl_client); getButton = (Button) findViewById (R. id. getbutton); colorEditText = (EditText) findViewById (R. id. coloredittext); weightEditText = (EditText) findViewById (R. id. weightedittext); // create the Intent intent = new Intent (); intent. setAction ("org. crazyit. aidl. action. AIDL_SERVICE "); // bindService (intent, conn, Service. BIND_AUTO_CREATE); getButton. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// obtain and display the remote service status try {colorEditText. setText (catService. getColor (); weightEditText. setText (catService. getWeight () + "");} catch (RemoteException e) {e. printStackTrace () ;}}) ;}@ Override protected void onDestroy () {super. onDestroy (); // unbind this. unbindService (conn );}}

      Error: java. lang. SecurityException: Binder invocation to an incorrect interface. Note that the server and client must have the same interface (used). the "same" here means the same interface, including the package name, that is to say, the same package name should be created under different projects.

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.