Android uses "Aidl" to invoke the workaround for external services _android

Source: Internet
Author: User
Tags int size stub

There is a service in Android that says it's a service, and it's an interface called Android Interface Definition Language, which provides access across processes, abbreviated as: Aidl.

The benefit of such a service is that there is a common service mechanism between multiple applications, sharing and data interoperability between different applications through Aidl, and a demo demo of how Aidl provides services between applications.
This article outlines the following:
• 1, create the Aidl service end.
• 2, create aidl client.
• 3, the client invokes the service interface provided by the server.
• 4, summary.
The functionality to be implemented in this article is as follows: Create AIDL server, this server will provide a student JavaBean to provide client access to data, because the AIDL support data type is relatively simple, it is recommended that the commonly used data types of data writing services.
1. Create Aidl service End
Create a new file in any package under the Android src folder, with the suffix named *.aidl, as shown below



Enter the following code:

Copy Code code as follows:

Package com.aidl.test;
Import com.aidl.test.Student;
Interface Imyservice
{
Map Getmap (in String test_class,in Student Student);
Student getstudent ();
}

The Student class is a serialized class where using the Parcelable interface to serialize is a more efficient serialization class that Google offers than serializable. The Student class code is as follows:
Copy Code code 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);
}
}

It is important to note here that the following three points must be noted 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
• Write the value you want to serialize into the parcel object in the Writetoparcel method.
• Write student last, you must create a new Student.aidl file, this file enter the following:
Parcelable Student; The writing here is for the interface *.aidl file that we mentioned above can be found, and find the Student class object through this file.
If the above steps pass smoothly, Android will automatically generate a *.java file named after the *.aidl file in the same directory of R files in the Gen directory, as shown in the following figure:

After successful build success, we will write a Aidl service class, the code is as follows:

Copy Code code 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", "Grade Five");
Map.put ("Age", Student.getage ());
Map.put ("Name", Student.getname ());
return map;
}
}
}

As the code above, the MyService service class has a subclass and inherits from the *.java file we generated above to rewrite the two interface methods that we have declared in *.aidl to achieve its function. 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, then it is necessary to register the service class in the manifest file, the following code:
Copy Code code as follows:

<service android:name= ". MyService ">
<intent-filter>
<action android:name= "Com.aidl.test.IMyService" ></action>
</intent-filter>
</service>

At this point, the service side has been developed and completed, and then the development of the client.

2. Create Aidl Client
The same is a new project, here to note that the server will be generated after the success of the Gen directory to copy the package, put into the src folder of our new project, the following figure:



Because Imyservice this generation class, references to the student this javabean so here will be JavaBean also copied over.
At this point, the client's creation has been completed, the following we will use the client created to invoke the method of the service side.

3, the client invokes the service interface provided by the server
Let's take a look at the effect of the operation:



Careful friends will find that the above data is not our client for student set the data? How did you get the same in this program? That's right. This is the charm of aidl, let's see how to call it, the figure has two buttons, a button for the binding Aidl service, that is, through the activity of the Bindservice binding aidl external services, all the code as follows:

Copy Code code 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 the activity is a. */
@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 is:" + myservice.getstudent (). GetName () + "\ n");
Sb.append ("Age is:" + myservice.getstudent (). Getage () + "\ n");
Sb.append ("Map object content 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 ("Invoke external service")
. Setmessage (Sb.tostring ()). Setpositivebutton (
Android. R.string.ok, NULL). Show ();
Break
Default
Break
}
}
}

Initialize the imyservice inside the serviceconnetction, and you can manipulate the object to get all the data we want to work with.

4. Summary
aidl file calls JavaBean Aidl file must guide the package;
JavaBean must be serialized, if not with JavaBean can be replaced with a simple variable, such as returning an integral type, return a string, and so on.
• The use of aidl must exist at the same time both the client and the server side, that is, the client on the computer, the server is also on the computer, to use the client must be the server in advance to register services on this machine.
Code Download: Service-side Demo
      Client Demo

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.