Android:service's Aidl transmission system basic type data

Source: Internet
Author: User
Tags abstract bind stub

What is Aidl?

To recap how Android interacts with other components in a local service, first the service must implement its Onbind () method and then pass the implementation of a IBinder interface in the Onbind method. In other components, the Bindservice () is used to bind a service, and then the parameter Serviceconnection object is obtained to implement the IBinder interface defined in the service. Then the data interaction with the service, in fact, is to pass a ibinder, through this ibinder to interact.

And now there is a problem, in the same process, you can get this service class, you can get the service defined in the IBinder, but if in different applications, that is, remote services, how to obtain IBinder? It's no use just to define a similar class in a different application, so Android provides us with the Aidl language, which needs to define a remote calling interface and then provide an implementation class for that interface, and share this remote calling interface to achieve data interaction between processes. The code for this interface has a lot in common, and the writing process is pretty boring, so the Android developer provides us with the Adil to simplify the development of the communication interface.

Aidl (Android Interface definition Language) is the definition language for the Android Remote call interface. It has its own set of grammatical specifications, but similar to Java, this is not difficult to understand, detailed this will be described later. And when you define a AIDL interface, you will find that in the gen/directory, a Java class with the same filename as the defined AIDL package name, which is automatically generated by the compiler based on the defined Aidl interface, observes that it also inherits the Binder class ( Binder is the IBinder implementation Class), so it can be passed through the serviceconnection. The service simply exposes the Aidl interface to the client and lets the client define it so that two application processes can be communicated.

How do I define aidl?

Aidl syntax is very similar to the syntax of the Java interface, but there are some differences:

Aidl to define the source code suffix of an interface must end with. Aidl.

Aidl to specify the package information for the Aidl interface package *.

The Aidl interface does not need to specify the scope of public, private, and protected, which can be understood to be public.

Aidl by default, only basic types, String, List, Map, and charsequence can be passed.

If you need to pass other types of objects, you need the package name of the import object, and you need to specifically handle the object (described later).

For example:

1 package com.example.aidlservicedemo.domain;

2

3 Interface idog{

4 String getName ();

5 int getage ();

6}

What did Adil do?

When you declare a AIDL interface, you will find in the project's gen/directory, the corresponding package has a Java file with the same name, this file is Android to help us automatically generated, there are a lot of code, here only to pay attention to. Looking at this auto-generated Java file code, you'll find that it defines a static abstract class named stub that inherits Binder, implements the Aidl interface, and, of course, implements the two methods of the Aidl interface. A cursory look at it will show that it does a serialization and deserialization operation on the data. Because Aidl is serialized and deserialized on the data, it can be passed between processes.

Using Adil to deliver system basic data

After defining the Aidl interface, it is necessary to expose the interface to the client through the service, where Service.onbind () is passed the implementation class of the stub static abstract class, and nothing else is special.

Below through a demo to demonstrate how Adil data, in the example, given two applications, respectively, to implement the server and invoke the client, the Aidl interface is given above the Aidl sample code, which is no longer repeated definitions.

Aidl Service: Basetypeservice.java

1 package Com.example.aidlservicedemo;

2

3 Import Java.util.Random;

4

5 Import com.example.aidlservicedemo.domain.IDog.Stub;

6

7 Import Android.app.Service;

8 Import android.content.Intent;

9 Import Android.os.IBinder;

Import android.os.RemoteException;

Import Android.util.Log;

12

public class Basetypeservice extends Service {

Private final String tag= "main";

Private Dogbinder Binder=null;

The private string[] names=new string[]{"small white", "flourishing wealth", "small Black"};

int[private] ages=new int[]{1,2,3};

18

19/**

The implementation class of the stub implements the binder inside the stub

21 * Internal implementation of Aidl definition method

22 */

public class Dogbinder extends stub{

24

@Override

Num public String GetName () throws RemoteException {

Random random=new Random ();

int nextint = Random.nextint (2);

return Names[nextint];

30}

31

@Override

The public int getage () throws RemoteException {

Random random=new Random ();

KM INT nextint = Random.nextint (2);

return Ages[nextint];

37}

38}

39

@Override

The public void OnCreate () {

Super.oncreate ();

43//Instantiation of Binder Object

Binder=new Dogbinder ();

LOG.I (TAG, "Create service Success");

46}

47

@Override

IBinder Onbind (Intent Intent) {

LOG.I (TAG, "Binding service Success");

51//Return Binder Object

Binder return;

53}

54}

The client invokes the service to get the data:

1 package Com.example.aidlClientdemo;

2

3 Import Com.example.aidlservicedemo.domain.IDog;

4 Import android.app.Activity;

5 Import Android.content.ComponentName;

6 Import android.content.Intent;

7 Import android.content.ServiceConnection;

8 Import Android.os.Bundle;

9 Import Android.os.IBinder;

Import Android.view.View;

Import Android.view.View.OnClickListener;

Import Android.widget.Button;

Import Android.widget.Toast;

14

public class Basetypeactivity extends activity {

Private Button Btn_startservice, Btn_endservice,btn_getservicedata;

Idog private Dogservice;

18

@Override

protected void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.activity_service);

23

Btn_startservice = (Button) Findviewbyid (R.id.btn_startservice);

Btn_endservice = (Button) Findviewbyid (R.id.btn_endservice);

Btn_getservicedata = (Button) Findviewbyid (r.id.btn_getservicedata);

27

Btn_startservice.setonclicklistener (click);

Btn_endservice.setonclicklistener (click);

Btn_getservicedata.setonclicklistener (click);

31}

32

The private View.onclicklistener click = New Onclicklistener () {

34

@Override

The public void OnClick (View v) {

Notoginseng switch (V.getid ()) {

Case R.id.btn_startservice:

StartService ();

break;

Case R.id.btn_endservice:

Endservice ();

The break;

Case R.id.btn_getservicedata:

Getservicedate ();

The break;

47}

48}

49};

50/*

51 * Obtaining data

52 */

The private void Getservicedate () {

The try {

if (dogservice!=null) {

StringBuilder sbuilder=new StringBuilder ();

Sbuilder.append ("Name:" +dogservice.getname ());

Sbuilder.append ("Nage:" +dogservice.getage ());

Toast.maketext (Basetypeactivity.this, sbuilder.tostring (), Toast.length_short). Show ();

60}

Or else

62 {

Toast.maketext (Basetypeactivity.this, "Please bind service first", Toast.length_short). Show ();

64}

' Exception ' catch (e) {

E.printstacktrace ();

67}

68}

69

Serviceconnection private Connbase=new serviceconnection () {

71

@Override

The public void onservicedisconnected (componentname name) {

The Dogservice=null;

75}

76

@Override

The public void onserviceconnected (componentname name, IBinder service) {

I//IDog.Stub.asInterface, get the interface

Dogservice=idog.stub.asinterface (service);

81}

82};

83

84/**

85 * Start Service

86 */

The private void StartService () {

Intent intent=new Intent ();

Intent.setaction ("Cn.bgxt.Service.BASE_TYPE_SERVICE");

Bindservice (Intent, connbase, bind_auto_create);

Toast.maketext (Basetypeactivity.this, "Start binding Service", Toast.length_short). Show ();

92}

93/**

94 * Stop Service

95 */

private void Endservice () {

if (connbase!=null)

98 {

Unbindservice (connbase);

100//Contact bindings need to recycle Dogservice connection resources

101//In the source of the leak, this is added later

102 Dogservice=null;

Toast.maketext (basetypeactivity.this, "Service Unbound", Toast.length_short). Show ();

104}

105}

106}

Effect Show: First run the service application, then run the client application.

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.