Android IPC interprocess communication with the latest Androidstudio aidl operations) _android

Source: Internet
Author: User
Tags file copy int size stub

Objective

What is the relationship between thread, handler, and Handlerthread in front of the threads that combed Android? These are all in the same process, the communication between processes, or the communication between different applications how to achieve it? This is the time to use Aidl (the Android Interface definition Languageandroid Interface Definition language).

How to use (Androidstudio)

I found that the Aidl tutorial is basically eclipse, but there are some different ways to use Aidl in Androidstudio, to see how to use it, first create a new project as a Server service:

After you have created the right key to New-->aidl-->aidl file in any folder, edit the file name automatically under the Src/main directory to create a new Aidl folder, the directory structure of the package is as follows:

Main
Aidl
Com.example.tee.testapplication.aidl
Java
Com.example.tee.testapplication
Res
Androidmanifest.xml

The aidl files are automatically generated as follows:

Aidlinterface.aidl
package com.example.tee.testapplication.aidl;

Declare any Non-default types-with import statements

interface Aidlinterface {
 /**
 * demonstrates some Basic types can use as parameters * and return
 values in Aidl.
 *
 /void basictypes (int anint, long along, Boolean aboolean, float afloat,
 double adouble, String astring);


We can see that the code format of the Aidl file is similar to Java, supporting the Java base type as well as list, map, and so on, if the custom class needs to be manually imported, we say later, first to the simplest, a new Imyaidlinterface.aidl file, modified as follows:

Package com.example.tee.testapplication.aidl;

Interface Imyaidlinterface {
 String getValue ();
}

Define a GetValue method in the interface, return a string, now you can compile the project, find the App/build/generated/source/aidl/debug directory, in our application package name will be found to generate a interface class, The name is the same as the Aidl file name we defined, which means that the Aidl file is eventually converted into an interface to implement, and this file does not need to be maintained and automatically generated after compilation.

Then create a new class to inherit the service:

public class Maidlservice extends service{public
 class Maidlserviceimpl extends
 @ Override public
 String GetValue () throws RemoteException {return
 ' get value ';
 }
 }
 @Nullable
 @Override public
 ibinder onbind (Intent Intent) {return
 new Maidlserviceimpl ();
 }
}

Define an inner class inheritance imyaidlinterface.stub in the Maidlservice class, and override the GetValue method that we defined in Aidl, which is the interface, returns the string get value.

When we get here, we're done with the new server, which is to return a string after the call and then declare it in the Androidmanifest file:

<service
 android:name= ". Maidlservice "
 android:process=": Remote//Plus this sentence the client invocation creates a new process
 android:exported= "true"//default to True, can be removed, Declares whether
 the > <intent-filter>
 <category android:name= can be invoked remotely Android.intent.category.DEFAULT "/>
 <action android:name=" Com.example.tee.testapplication.aidl.IMyAidlInterface "/>
 </ Intent-filter>
</service>

The

android:process= ": remote" function is to declare whether a new process is invoked, write the client code, create a new project, copy the Aidl file that you just created to the project, and note that it is also placed under the Aidl folder. Then write the code in Mainactivity as follows:

public class Mainactivity extends Appcompatactivity {private TextView Mvaluetv;
 Private Imyaidlinterface maidlinterface = null; Private Serviceconnection mserviceconnection = new Serviceconnection () {@Override public void onserviceconnected (compon
 Entname name, IBinder service) {maidlinterface = IMyAidlInterface.Stub.asInterface (service);
 @Override public void onservicedisconnected (componentname name) {}}; @Override protected void OnCreate (Bundle savedinstancestate) {Intent Intent = new Intent ("Com.example.tee.testapplicati
 On.aidl.IMyAidlInterface ");
 Bindservice (Intent, mserviceconnection, bind_auto_create);
 Mvaluetv = (TextView) Findviewbyid (R.id.tv_test_value); Mvaluetv.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {try {Mvaluetv.sette
 XT (Maidlinterface.getvalue ());
 catch (RemoteException e) {e.printstacktrace ();
 }
 }
 }); } @Override protected void OnDestroy () {if (maidlinterface!= null) {UnbindseRvice (mserviceconnection);
 } Super.ondestroy ();

 }
}

Note that the incoming parameter string for the new intent here is a custom action tag inside manifest, and in OnDestroy Remember to unbind the service.

The result is that we will display the get value string returned by the server to us when we click TextView

Custom Objects

Just now we are using the base type string, the above method is not good when we use our own defined class, we need to import the custom class manually, modify the project we just created as the service side.

First, under the Aidl package that starts the build (all aidl related files are placed under this package) new Student.java

 public class Student implements parcelable{public String name;
 public int age;
 Protected Student (Parcel in) {Readfromparcel (in);
 Public Student () {} public static final creator<student> Creator = new creator<student> () {@Override
 Public Student Createfromparcel (Parcel in) {Return to New Student (in);
 @Override public student[] NewArray (int size) {return new student[size];

 }
 };
 @Override public int describecontents () {return 0;
 @Override public void Writetoparcel (Parcel dest, int flags) {dest.writeint (age);
 Dest.writestring (name);
 public void Readfromparcel (Parcel in) {age = In.readint ();
 Name = In.readstring ();
 @Override public String toString () {return String.Format (Locale.english, ' student[%s:%d] ', name, age); }
}

Need to implement Parcelable serialization interface, Androidstudio will automatically generate static internal class creator and Describecontents methods, these parts we do not need to modify, with automatic generation is good. Then rewrite the Writetoparcel method, customize the Readfromparcel method, and note that the order of the attributes in the two methods must be consistent, one to write, and one to read. Call the Readfromparcel (in) method in constructor student (Parcel in).

Next, create a new Student.aidl file (also in the Aidl package):

Student.aidl
package com.example.tee.testapplication.aidl;

Declare any non-default types, with import statements
parcelable Student;

Note Here student the previous keyword parcelable first letter is lowercase oh, and then modify Imyaidlinterface.aidl file as follows:

Imyaidlinterface.aidl
package com.example.tee.testapplication.aidl;

Declare any non-default types, with import statements
import com.example.tee.testapplication.aidl.student;< C9/>interface imyaidlinterface {
 Student getstudent ();
 void Setstudent (in Student Student);
 String GetValue ();
}

Defines two methods, one is to set student, one is to get student, in setstudent This method note that the parameter has an in keyword in front of the type, in the Aidl parameter is divided into input, out output

Now rewrite the newly added two methods in Maidlservice.java:

Private Student mstudent;
public class Maidlserviceimpl extends imyaidlinterface.stub{


 @Override public
 Student getstudent () throws remoteexception {return
 mstudent;
 }

 @Override public
 void Setstudent (Student Student) throws RemoteException {
 mstudent = Student;
 }

 @Override public
 String GetValue () throws RemoteException {return
 ' Get value: ' + thread.currentthread (). Getn Ame () + Thread.CurrentThread (). GetId ();
 }
}

Service-side code has been modified, came to the client project, the same to the Aidl package under the file copy covered, to maintain the two sides consistent, and then in the Mainactivity.java modified as follows:

Mvaluetv = (TextView) Findviewbyid (r.id.tv_test_value);
Mstudenttv = (TextView) Findviewbyid (r.id.tv_test_student);
Mvaluetv.setonclicklistener (New View.onclicklistener () {
 @Override public
 void OnClick (View v) {
 try {
 Mvaluetv.settext (Maidlinterface.getvalue ());
 } catch (RemoteException e) {
 e.printstacktrace ();}}}
);
Mstudenttv.setonclicklistener (New View.onclicklistener () {
 @Override public
 void OnClick (View v) {
 try {
 Student Student = new Student ();
 Student.age = ten;
 Student.name = "Tom";
 Maidlinterface.setstudent (student);
 Mstudenttv.settext (Maidlinterface.getstudent (). toString ());
 catch (RemoteException e) {
 e.printstacktrace ();}}}
);

Now compile the project, will find the project will error, can not find the class student, we need in the app directory Build.gradle file add code as follows:

Android {
 Sourcesets {
 main {
 manifest.srcfile ' src/main/androidmanifest.xml '
 java.srcdirs = [' src/ Main/java ', ' src/main/aidl ']
 resources.srcdirs = [' Src/main/java ', ' src/main/aidl ']
 aidl.srcdirs = [' src/ Main/aidl ']
 res.srcdirs = [' Src/main/res ']
 assets.srcdirs = [' Src/main/assets ']
 }
 }
}

That is to specify the file directory, and now the compilation will be no problem

Summarize

The Android IPC is very simple to use, Aidl file syntax is similar to our normal use of the interface, but it only supports the underlying type, only reference aidl files, need to use a custom class to a little bit of trouble.

The above is to the Android IPC process communication data collation, follow-up continue to supplement the relevant information thank you for your support of this site!

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.