An example of Aidl interprocess communication in Android _android

Source: Internet
Author: User
Tags gettext stub

With regard to IPC should not be introduced, the Android system can not share the memory between the processes, so if the two different applications need to communicate with each other? For example, a company's project to update, product requirements are attached to the current project to develop a plug-in, but this plug-in function and interface is more complex, not with the current project in a process, but also to use the current project has written some things, Because the newly developed plug-in and current project attached to the current project is not a process, and therefore cannot share memory, there is a problem, so there is a need to provide some mechanism for data communication between different processes, this mechanism is aidl.

A simple example of aidl in de jure Android

If so, now there is a project to provide a more mature method of calculation, and now I want to develop a software one of the modules want to use a computing class, and I do not want to write again, then it can be implemented through the aidl. Suppose that the program that has been developed that has provided a more mature computing class is called aidlcalculatedemoserver (the equivalent of a server), and the program I'm writing is called aidlcalculatedemoclient (the equivalent of a client), Similar to the client server mode. First of all, look down the engineering structure:
Figure 1-1 Server Figure 1-2 Client

Now assume that the program you write to invoke the operational interface of the server, input NUM1 and num2, remote operations, invoke the interface of the server, the service end of the operation, return the results to the client, the effect diagram is as follows:
Then take a look at the implementation, first you need to define the Aidl interface, the client and server side are defined, and in the same package, which is the calculateinterface in Figure 1-1 and figure 1-2 Com.example.aidl.calculate, where the code is as follows:

Package com.example.aidl.calculate;

Interface Calculateinterface {
  double docalculate (double A, double b);
 }

Compilation found that the directory structure, as shown in Figure 1-1 and figure 1-2, gen/com.example.aidl.calculate more Calculateinterface.java files, as follows:

 Package com.example.aidl.calculate;
 
Interface Calculateinterface {
   double docalculate (double A, double b);
 }

The definition of interface is to look at the server and client code, where the server mainly look at the Calculateservice code, this one inherits the service class, in which the interface in Aidl to give practical significance, as follows:

 Package com.example.calculate;
Import Com.example.aidl.calculate.CalculateInterface;

Import com.example.aidl.calculate.CalculateInterface.Stub;
Import Android.app.Service;
Import android.content.Intent;
Import Android.os.IBinder;
Import android.os.RemoteException;

Import Android.util.Log; public class Calculateservice extends Service {private static final String TAG = "Calculate
  
  Service ";
    @Override public IBinder onbind (Intent arg0) {//TODO auto-generated Method Stub LogE ("Onbind ()");
  return mbinder;
    @Override public void OnCreate () {//TODO auto-generated Method Stub LogE ("OnCreate ()");
  Super.oncreate (); @Override public void OnStart (Intent Intent, int startid) {//TODO auto-generated Method Stub LogE ("Onst
    Art () ");
  Super.onstart (Intent, Startid); 
    @Override public boolean onunbind (Intent Intent) {//TODO auto-generated the method stub LogE ("Onunbind ()"); return suPer.onunbind (Intent);
    @Override public void OnDestroy () {//TODO auto-generated Method Stub LogE ("OnDestroy ()");
  Super.ondestroy ();
  private static void LogE (String str) {LOG.E (TAG, "--------" + str + "--------"); Private final Calculateinterface.stub Mbinder = new Calculateinterface.stub () {@Override public doubl E docalculate (Double A, double b) throws RemoteException {//TODO auto-generated Method Stub log.e ("Calculate
      "," Remote Computing ");
      Calculate Calculate = new Calculate ();
      Double answer = Calculate.calculatesum (A, b);
    return answer;
}
  };

 }

You can then look at how the key services are available, and how the client is accessed, the binding service and a Serviceconnection class complete, as follows:

Package com.example.calculate;
Import android.app.Activity;
Import Android.content.ComponentName;
Import Android.content.Context;
Import android.content.Intent;
Import android.content.ServiceConnection;
Import Android.graphics.Color;
Import Android.os.Bundle;
Import Android.os.IBinder;
Import android.os.RemoteException;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;

Import Android.widget.TextView;
Import Com.example.aidl.calculate.CalculateInterface;

Import COM.EXAMPLE.AIDLCALCULATEDEMOCLIENT.R; public class Calculateclient extends activity {private static final String TAG = "Calculateclie
  
  NT ";
  
  Private Button btncalculate;
  
  Private EditText etNum1;
  
  Private EditText etNum2;
  
  Private TextView Tvresult;
  
  Private Calculateinterface Mservice; Private Serviceconnection mserviceconnection = new ServiCeconnection () {@Override public void onservicedisconnected (componentname name) {//TODO Auto-generat
      Ed method Stub LogE ("Disconnect service");
    Mservice = null; @Override public void onserviceconnected (componentname name, IBinder service) {//TODO auto-generate
      D Method Stub LogE ("Connect service");
    Mservice = CalculateInterface.Stub.asInterface (service);
  
  }
  }; @Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method stub super.oncreate
    (savedinstancestate);
    
    Setcontentview (R.layout.main);
    Bundle args = new Bundle ();
    Intent Intent = new Intent ("Com.example.calculate.CalculateService");
    Intent.putextras (args);
    
    Bindservice (Intent, mserviceconnection, context.bind_auto_create);
    ETNUM1 = (edittext) Findviewbyid (R.id.et_num_one);
    
    etNum2 = (edittext) Findviewbyid (r.id.et_num_two); Tvresult = (TextView) Findviewbyid (r.id.tv_result);
    
    Btncalculate = (Button) Findviewbyid (r.id.btn_cal);
        Btncalculate.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
        TODO auto-generated Method Stub LogE ("Start remote operation");
          try {Double num1 = double.parsedouble (Etnum1.gettext (). toString ());
          Double num2 = double.parsedouble (Etnum2.gettext (). toString ());
          String answer = "Calculated result:" + mservice.docalculate (NUM1, num2);
          Tvresult.settextcolor (Color.Blue);
              
        Tvresult.settext (answer);
  catch (RemoteException e) {}}});
  private void LogE (String str) {LOG.E (TAG, "--------" + str + "--------");

 }
}

In this way, the success has been basically done, and finally, we look at the service-side configuration file bar:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" Com.example.aidlcaculatedemoserver "android:versioncode=" 1 "android:versionname=" 1.0 "> < USES-SDK android:minsdkversion= "8" android:targetsdkversion= "a"/> <application android:allowBackup= "True" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" &
    Gt <activity android:name= "com.example.aidlcaculatedemoserver.MainActivity" android:label= "@string/app_name" &
      Gt <intent-filter> <action android:name= "Android.intent.action.MAIN"/> <category Android:nam E= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <service android:name = "Com.example.calculate.CalculateService" > <intent-filter> <action android:name= "com.example.cal Culate. CalculateserVice "/> </intent-filter> </service> </application> </manifest>

 

Second, write Aidl notice matters

1. Client and server-side Aidl interface files must be in the same package

2. Need a service type of coordination

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.