In Android, there is a service called a service, which is actually an Interface called: Android Interface Definition Language. This Interface can provide cross-process access services, abbreviated as AIDL.
The benefit of this service is that a common service mechanism is established between multiple applications to achieve data sharing and data operations among different applications through AIDL, the following DEMO demonstrates how AIDL provides services between applications.
The outline of this article is:
• 1. Create an AIDL server.
• 2. Create an AIDL client.
• 3. The client calls the service interface provided by the server.
• 4. Summary.
The functions to be implemented in this article are roughly as follows: To create an AIDL server, this server will provide a Student javabean to provide the client to obtain data, because the data types supported by aidl are relatively simple, therefore, we recommend that you write data of common data types to the service.
1. Create an AIDL Server
Create a file in any package in the src folder of Android with the suffix *. aidl, as shown in figure
Enter the following code:
Copy codeThe Code is as follows: package com. aidl. test;
Import com. aidl. test. Student;
Interface IMyService
{
Map getMap (in String test_class, in Student student );
Student getStudent ();
}
Student class is a serialized class. The Parcelable interface is used to serialize A serialization class provided by Google, which is more efficient than Serializable. The Student class code is as follows:Copy codeThe Code is as follows: package com. aidl. test;
Import android. OS. Parcel;
Import android. OS. Parcelable;
Public class Student implements Parcelable {
Private int age;
Private String name;
Public int getAge (){
Return age;
}
Public void setAge (int age ){
This. age = age;
}
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
Public static final Parcelable. Creator <Student> CREATOR = new Creator <Student> (){
@ Override
Public Student [] newArray (int size ){
// TODO Auto-generated method stub
Return new Student [size];
}
@ Override
Public Student createFromParcel (Parcel source ){
// TODO Auto-generated method stub
Return new Student (source );
}
};
Public Student (){
}
Public Student (Parcel pl ){
Age = pl. readInt ();
Name = pl. readString ();
}
@ Override
Public int describeContents (){
// TODO Auto-generated method stub
Return 0;
}
@ Override
Public void writeToParcel (Parcel dest, int flags ){
// TODO Auto-generated method stub
Dest. writeInt (age );
Dest. writeString (name );
}
}
Note the following three points when writing javabean:
• There must be a static constant in the Student class, the constant name must be CREATOR, and the Data Type of the CREATOR constant must be Parcelable. Creator
• The value to be serialized must be written into the Parcel object in the writeToParcel method.
• After writing Student, you must create another Student. aidl file, which includes the following content:
Parcelable Student; the description here is for the interface *. aidl File Export package that we mentioned above, and the Student class object can be found through this file.
If the preceding steps are successful, Android will automatically generate a *. java file named *. aidl file in the same directory of the R file under the gen directory, for example:
After successful generation, we will compile an AIDL service class. The Code is as follows:
Copy codeThe Code is as follows: package com. aidl. test;
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 {
@ Override
Public IBinder onBind (Intent intent ){
// TODO Auto-generated method stub
Return new MyServiceimpl ();
}
Public class MyServiceimpl extends IMyService. Stub {
@ Override
Public Student getStudent () throws RemoteException {
// TODO Auto-generated method stub
Student st = new Student ();
St. setAge (18 );
St. setName ("terry ");
Return st;
}
@ Override
Public Map getMap (String testClass, Student student)
Throws RemoteException {
// TODO Auto-generated method stub
Map <String, Object> map = new HashMap <String, Object> ();
Map. put ("class", "fifth grade ");
Map. put ("age", student. getAge ());
Map. put ("name", student. getName ());
Return map;
}
}
}
In the above Code, the MyService service class has a subclass that inherits the *. java file generated above and overwrites the two interface methods we declare in *. aidl to implement its functions. The above IBinder must return the subclass object of this service class, otherwise the client will not be able to obtain the service object.
Finally, if there is a service operation, you have to register the service class in the manifest file. The Code is as follows:Copy codeThe Code is as follows: <service android: name = ". MyService">
<Intent-filter>
<Action android: name = "com. aidl. test. IMyService"> </action>
</Intent-filter>
</Service>
Now, the server has been developed. Next we will start the development client.
2. Create an AIDL Client
You need to copy the packages under the gen directory generated by the server and put them in the src folder of the newly created Project, for example:
Because the IMyService generated class references the Student javabean, the javabean is also copied here.
So far, the creation of the client has been completed. Next we will use the created client to call the method of the server.
3. The client calls the service interface provided by the server.
Let's take a look at the running effect:
Careful friends will find that the above data is not the data we set for Student on the client above? How can we get the same result in this program? Yes. This is the charm of aidl. Let's take a look at how to call it. There are two buttons in the figure. One button is bound to the AIDL service, that is, bind the AIDL external service through the bindService of the Activity. All the code is as follows:
Copy codeThe Code is as follows: package com. aidl. client;
Import com. aidl. test. IMyService;
Import android. app. Activity;
Import android. app. AlertDialog;
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. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Public class aidlActivity extends Activity implements OnClickListener {
Button btn1, btn2;
Private IMyService myService = null;
Private ServiceConnection serviceConnection = new ServiceConnection (){
@ Override
Public void onServiceDisconnected (ComponentName name ){
// TODO Auto-generated method stub
}
@ Override
Public void onServiceConnected (ComponentName name, IBinder service ){
// TODO Auto-generated method stub
MyService = IMyService. Stub. asInterface (service );
Btn2.setEnabled (true );
}
};
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Btn1 = (Button) findViewById (R. id. Button01 );
Btn2 = (Button) findViewById (R. id. Button02 );
Btn2.setEnabled (false );
Btn1.setOnClickListener (this );
Btn2.setOnClickListener (this );
}
@ Override
Public void onClick (View v ){
// TODO Auto-generated method stub
Switch (v. getId ()){
Case R. id. Button01:
BindService (new Intent ("com. aidl. test. IMyService "),
ServiceConnection, Context. BIND_AUTO_CREATE );
Break;
Case R. id. Button02:
StringBuilder sb = new StringBuilder ();
Try {
Sb. append ("Student name:" + myService. getStudent (). getName () + "\ n ");
Sb. append ("Age:" + myService. getStudent (). getAge () + "\ n ");
Sb. append ("the content of the map object is as follows :"
+ MyService. getMap ("China", myService. getStudent ())
. ToString ());
} Catch (RemoteException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
New AlertDialog. Builder (aidlActivity. this). setTitle ("call external service ")
. SetMessage (sb. toString (). setPositiveButton (
Android. R. string. OK, null). show ();
Break;
Default:
Break;
}
}
}
Initialize the IMyService in ServiceConnetction to operate on this object. This object can get all the data to be processed.
4. Summary
• Aidl files must be imported into aidl files that call javabean;
• Javabean must be serialized. If javabean is not used, it can be replaced by simple variables, such as an integer or a string.
• To use aidl, both the client and the server must exist, that is, the client is on the local machine and the server is on the local machine. To use the client, the server must have registered the service on the local machine in advance.
Download Code:Server DEMO
Client DEMO