Android cross-process access (AIDL service)

Source: Internet
Author: User

I will summarize the learning knowledge of androidaidl and share with you

In Android development, AIDL is primarily used for cross-process access.

There is no sharing of memory between processes in the Android system, so there is a need to provide mechanisms for data communication between different processes, typically implemented with service services components.

1. Create Call Aidl Service

Steps to establish a AIDL service:

The first step: Create a file with the extension aidl in the Java source directory of the Eclipse Android project, and change the syntax of the file to resemble Java code, but slightly different.

Step two: If the contents of the Aidl file are correct, ADT will automatically generate a Java interface file in the Gen directory.

Step three: Set up a service class (subclass of Services).

Fourth step: Implement the Java interface with Aidl file generation.

Fifth step: Configure the Aidl service in the Androidmanifest.xml file, especially note that the attribute value Android:name in the,<action> tag is the ID of the client to reference the service, which is the parameter value of the intent class constructor method.

The following implements an example:

Imyservice.aidl: (In fact, the Java class defines the interface file in the form of some similar)

Package Mobile.android.aidl;interface imyservice{    String getValue ();}
Implementation of the Myservice.java class:

Package Mobile.android.aidl;import Mobile.android.aidl.imyservice;import Android.app.service;import Android.content.intent;import Android.os.ibinder;import Android.os.remoteexception;public class MyService extends service{public class Myserviceimpl extends imyservice.stub{@Overridepublic String getValue () throws remoteexception{// TODO auto-generated method Stubreturn "Android Deep Exploration (Vol. 1): Hal and Driver Development";}} @Overridepublic ibinder onbind (Intent Intent) {return new Myserviceimpl ();}}
In the configuration of the Androidmanifest.xml:

<service android:name= ". MyService "><span style=" White-space:pre "></span><intent-filter> <action android:name=" Mobile.android.aidl.IMyService "/>   <!--access to id--></intent-filter></service>
Client code:

Package Mobile.android.aidlclient;import Mobile.android.aidl.imyservice;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.view.View; Import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;import Android.widget.toast;public class Main extends Activity implements onclicklistener{private imyservice myservice = null; Private button Btninvokeaidlservice;private button btnbindaidlservice;private TextView textview;private Serviceconnection serviceconnection = new Serviceconnection () {@Overridepublic void onserviceconnected (componentname  Name, IBinder service) {MyService = IMyService.Stub.asInterface (service); Gets the service object btninvokeaidlservice.setenabled (TRUE);} @Overridepublic void onservicedisconnected (componentname name) {Toast.maketext (main.this, "Unable to connect", Toast.length_short ).Show (); btninvokeaidlservice.setenabled (true);}; @Overridepublic void OnClick (view view) {switch (View.getid ()) {case R.id.btnbindaidlservice:
<span style= "White-space:pre" ></span>//bind aidl Service if (!bindservice (New Intent (" Mobile.android.aidl.IMyService "), Serviceconnection, Context.bind_auto_create) toast.maketext (Main.this," Unable to connect ", Toast.length_short). Show (); Break;case R.id.btninvokeaidlservice:try{textview.settext (Myservice.getvalue ());} catch (Exception e) {textview.settext (E.getmessage ());} Break;}}  @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main) Btninvokeaidlservice = (Button) Findviewbyid (r.id.btninvokeaidlservice); btnbindaidlservice = (Button ) Findviewbyid (R.id.btnbindaidlservice); btninvokeaidlservice.setenabled (false); TextView = (TextView) Findviewbyid ( R.id.textview); Btninvokeaidlservice.setonclicklistener (this), Btnbindaidlservice.setonclicklistener (This);}}
Note the points:

1. Use the Bindservice method to bind the Aidl service. It is necessary to use the intent object to specify the ID of the Aidl service, which is the value android:name in the <action> tag when declaring the service.

2. A Serviceconnection object is required for binding. If the binding succeeds during the creation of the Serviceconnection object, the system calls the Serviceconnection.onserviceconnected method,

The service parameter value of the method is used to obtain the Aidl services object.

2. Aidl Service for transmitting complex data (custom type of data)

First, understand that the AIDL service only supports a limited number of data types, so if you pass some complex data with the AIDL service, you need to take a step further.

The supported data types for AIDL are as follows:

1. Java's simple type (int, char, Boolean), import is not required.

2, String and charsequence. Import imports are not required.

3, list and map. Note, however, that the list and map object element types must be data types supported by the AIDL service. Import imports are not required.

4, Aidl Auto-generated interface. Import imports are required. L

5, the implementation of the Android.os.Parcelable interface class. Import imports are required.

In the pass-through that does not require import imports, the delivery requires import imports (the class that implements the Android.os.Parcelable interface). In addition to creating a class that implements Android.os.Parcelable

Also create a separate aidl file for this class and define it using the Parcelable keyword.

Look at this example:

Registered configuration in Androidmanifest.xml:

<service android:name= ". MyService "><intent-filter> <action android:name=" Mobile.android.complex.type.aidl.IMyService "/> </intent-filter></service>
Imyservice.aidl:

Package Mobile.android.complex.type.aidl;import Mobile.android.complex.type.aidl.product;interface IMyService  {      Map getmap (in String country, in product product);    Product getproduct ();     }          
Product.java class:

Package Mobile.android.complex.type.aidl;import Android.os.parcel;import Android.os.parcelable;public class Product Implements Parcelable{private int id;private String name;private float price;public static final parcelable.creator< product> CREATOR = new parcelable.creator<product> () {public Product createfromparcel (Parcel in) {return new Product (in);}    Public product[] NewArray (int size) {return new product[size];}; Public product () {}private product (Parcel.) {readfromparcel (in);} @Overridepublic int describecontents () {//TODO auto-generated method Stubreturn 0;} public void Readfromparcel (Parcel in) {id = in.readint (), name = In.readstring ();p rice = In.readfloat ();} @Overridepublic void Writetoparcel (Parcel dest, int flags) {Dest.writeint (ID);d est.writestring (name);d est.writefloat (price);} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public float GetPrice () {REturn Price;} public void Setprice (float price) {this.price = Price;}}
Product.aidl: (mainly in aidl to declare the above custom type in order to be used in Imyservice)

Myservice.java class:

Package Mobile.android.complex.type.aidl;import Java.util.hashmap;import Java.util.map;import android.app.Service; Import Android.content.intent;import Android.os.ibinder;import android.os.RemoteException; public class MyService extends service{public class Myserviceimpl extends imyservice.stub{@Overridepublic Product Getpro Duct () throws remoteexception{product Product = new product ();p Roduct.setid (1234);p roduct.setname ("Car"); Product.setprice (31000); return product;} @Overridepublic map Getmap (string country, product product) throws Remoteexception{map map = new hashmap<string, string > (); Map.put ("Country", country), map.put ("id", Product.getid ()), Map.put ("name", Product.getname ()); Map.put (" Price ", Product.getprice ()); Map.put (" Product ", product); return map;}} @Overridepublic ibinder onbind (Intent Intent) {return new Myserviceimpl ();}}
To implement the AIDL service on the client:

Package Mobile.android.complex.type.aidlclient;import Mobile.android.complex.type.aidl.imyservice;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.view.view;import Android.view.view.onclicklistener;import Android.widget.Button Import Android.widget.textview;public class Main extends Activity implements Onclicklistener{private Imyservice MyService = null;private button btninvokeaidlservice;private button btnbindaidlservice;private TextView TextView; Private Serviceconnection serviceconnection = new Serviceconnection () {@Overridepublic void onserviceconnected ( ComponentName name, IBinder service) {MyService = IMyService.Stub.asInterface (service); Btninvokeaidlservice.setenabled (TRUE);} @Overridepublic void onservicedisconnected (componentname name) {//TODO auto-generated Method stub}}; @Overridepublic void OnClick(View view) {switch (View.getid ()) {case R.id.btnbindaidlservice:bindservice (new Intent (" Mobile.android.complex.type.aidl.IMyService "), Serviceconnection, context.bind_auto_create); break;case  r.id.btninvokeaidlservice:try{string s = ""; s = "product.id =" + myservice.getproduct (). GetId () + "\ n"; s + = "Product.name = "+ myservice.getproduct (). GetName () +" \ n "; s + =" Product.price = "+ myservice.getproduct (). GetPrice () +" \ n "; s + = Myser Vice.getmap ("China", Myservice.getproduct ()). ToString (); Textview.settext (s);} catch (Exception e) {}break;}} @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main) Btninvokeaidlservice = (Button) Findviewbyid (r.id.btninvokeaidlservice); btnbindaidlservice = (Button ) Findviewbyid (R.id.btnbindaidlservice); btninvokeaidlservice.setenabled (false); TextView = (TextView) Findviewbyid ( R.id.textview); Btninvokeaidlservice.setonclicklistener (this), Btnbindaidlservice.setonclicklistener (This);}}
Here in the implementation of an extended: Aidl and come to power automatically hang up

Although you can make a call with the activity action, you cannot hang up the phone using the usual method. However, the use of Java reflection technology is to implement a method of hanging up the phone through the program.

The following interfaces are available from the Android SDK Source:

Com,android.internal,telephony. Itelephony, external cannot be accessed directly, this interface provides a Itelephony.endcall method:

Although the Itelephony object cannot be accessed directly. However, the Telephonymanager class provides a Getitelepgony method that can return an Itelephony object. But this method is private, but

We can invoke this method through the reflection technology of Java. Before using Getitelephony to obtain Itelephony objects, locate the Neighboringcellinfo.aidl and Itelephony.aidl files in the Android SDK directory

Copy to your project directory.

ADT automatically generates Itelephony.java files based on the Itelephony.aidl file.

Here is a broadcast incoming call is the first to automatically hang up the designated phone calls:

Package Mobile.android.call.aidl;import Java.lang.reflect.method;import Com.android.internal.telephony.ITelephony ; Import Android.app.service;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.telephony.telephonymanager;import Android.widget.toast;public Class Incallreceiver extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) { Telephonymanager TM = (Telephonymanager) context.getsystemservice (service.telephony_service); switch ( Tm.getcallstate ()) {case telephonymanager.call_state_ringing://Ring//Get the phone number of the call string Incomingnumber = Intent.getstringextra ("Incoming_number"); if ("12345678". Equals (Incomingnumber)) {Try{telephonymanager Telephonymanager = (Telephonymanager) context.getsystemservice (Service.telephony_service); class<telephonymanager> telephonymanagerclass = Telephonymanager.class; Method Telephonymethod = Telephonymanagerclass.getdeclaredmethod ("Getitelephony", (class[]) NULL); telEphonymethod.setaccessible (true); Itelephony telephony = (com.android.internal.telephony.ITelephony) Telephonymethod.invoke (Telephonymanager, (object[]) null); Telephony.endcall ();} catch (Exception e) {toast.maketext (context, E.getmessage (), Toast.length_long). Show ();}} Break;}}}

The above is a summary of the understanding of AIDL services, I hope that useful to everyone, welcome to learn and guide together.




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android cross-process access (AIDL service)

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.