Analysis of the principle of _android communication between the Android process

Source: Internet
Author: User
Tags documentation prepare stub

The Android service is divided into two types:
Local Service: The same apk is called
Remote service: Called by another apk
The remote service needs to be done with the help of Aidl.

What's aidl?
Aidl (Android Interface Definition Language) is an IDL language used to generate interprocess communication between two processes on an Android device (interprocess communication, IPC) The code. If you are in a process, such as an activity, to invoke an operation on another process (such as a service) object, you can use Aidl to generate serializable parameters.
The AIDL IPC mechanism is interface-oriented, like COM or CORBA, but more lightweight. It is the use of proxy classes to pass data on both the client and the implementation side.

The role of Aidl
Because each application runs in its own process space and can run another service process from the application UI, it often passes objects between different processes. On the Android platform, a process usually does not have access to the memory space of another process, so in order to be able to talk, the object needs to be decomposed into basic units that the operating system understands, and is ordered through the process boundary.
Using code to implement this data transfer process is tedious, and Android provides aidl tools to handle this work.

Choose the occasion of Aidl
The official documentation specifically reminds us when using aidl is necessary: Only you allow clients to access your service from different applications for interprocess communication, and to handle multithreading in your service.
If you do not need concurrent communication (IPC) between different applications, you can should create your interface by implementing a Binder, or you want to do IPC, but do not need to handle multithreading, then implement your interface using a Messenger. In any case, before using Aidl, you must understand how to bind Service--bindservice.

The following example will be given from: http://www.cnblogs.com/lonkiss/archive/2012/10/23/2735548.html

Below is a demo of the use of aidl using an instance of a client-side activity Server service to play music.

Server-side code structure (left) client code structure (right)
What is marked is the need to do it.
Service side

Create a new Android application project, named Playerserver. In the raw folder under Res put a music file, I put here is Delta Goodrem's "Lost Without You" fragment. If you do not have raw this folder, create a new one, named Raw. This file is clipped to the raw folder and is layout to the folder. The files in raw are subject to the naming rules for identifiers, do not appear in Chinese and spaces, and multiple words can be connected by underlining.
  
Create a new Iremoteserviice.aidl file and add the following code

Copy Code code as follows:

Package pandafang.demo.playerserver;
Interface Iremoteservice {
void Play ();
void Stop ();
}

The code for the visible aidl file is the same as the Java interface, but the aidl cannot add a modifier such as public. Ctrl + S Save ADT will automatically generate Iremoteservice.java files based on this iremoteservice.aidl file. Like R.java files under "gen/package name," The code is automatically generated and not manually modified.
  
The next step is the knowledge of bound service. There is a stub static abstract class extends Binder implements Iremoteservice in Iremoteservice.java. Write yourself a playerservice used to play music, play music need to use

Android.media.MediaPlayer class. The code is as follows

Copy Code code as follows:

/**
* Services to play Music
*/
public class Playerservice extends Service {

public static final String TAG = "Playerservice";

Private MediaPlayer MPlayer;

@Override
Public IBinder Onbind (Intent Intent) {
LOG.I (TAG, "service Onbind");
if (mplayer==null) {
Method One description
This method instantiates the player while specifying the music data source, and if you use this method to Mplayer.start (), you do not need to call Mplayer.prepare ()
Official documentation notes: On success, prepare () 'll already have been called and must not to called again.
Once the Create is successful, prepare has been invoked and not called again. View source code you have already called the prepare method inside the Create method.
Method at the outset
MPlayer = Mediaplayer.create (this, r.raw.lost);
End of Method One

Method two illustrates
If you use this method, you need to invoke Mplayer.prepare () before Mplayer.start ()
Method Two begins
MPlayer = new MediaPlayer ();
try {
FileDescriptor fd = Getresources (). OPENRAWRESOURCEFD (R.raw.lost). Getfiledescriptor (); Get Music data source
Mplayer.setdatasource (FD); Setting up a data source
Mplayer.setlooping (TRUE); Set to loop playback
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Method two ends
LOG.I (TAG, "player created");
}
return mbinder;
}

implementing interfaces defined in the Aidl file
Private IBinder Mbinder = new Iremoteservice.stub () {

@Override
public void Stop () throws RemoteException {
try {
if (mplayer.isplaying ()) {
Mplayer.stop ();
}
catch (Exception e) {
Todo:handle exception
E.printstacktrace ();
}
}

@Override
public void Play () throws RemoteException {
try {
if (mplayer.isplaying ()) {
Return
}
Need to prepare before start.
If you use method one when you instantiate the MPlayer, the first play will start directly without prepare.
But after the stop, play again needs to be prepare before start.
Use the previous method two here is easy, do not judge the various conditions
Mplayer.prepare ();
Mplayer.start ();
catch (Exception e) {
Todo:handle exception
E.printstacktrace ();
}
}
};
@Override
public boolean onunbind (Intent Intent) {
if (MPlayer!= null) {
Mplayer.release ();
}
LOG.I (TAG, "service Onunbind");
return Super.onunbind (Intent);
}
}

After the service is written, follow the conventions of adding a declaration to the Androidmanifest.xml code as follows
Copy Code code as follows:

<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"
Package= "Pandafang.demo.playerserver"
Android:versioncode= "1"
Android:versionname= "1.0" >
<uses-sdk
Android:minsdkversion= "8"
Android:targetsdkversion= "/>"
<application
android:icon= "@drawable/ic_launcher"
Android:label= "@string/app_name"
Android:theme= "@style/apptheme" >
<service android:name= ". Playerservice "android:process=": Remote ">
<intent-filter >
<action android:name= "Com.example.playerserver.PlayerService"/>
</intent-filter>
</service>
</application>
</manifest>

Need to join is only <service>...</service> that paragraph, should pay attention to is android:process= ": Remote" and intent-filter.
Run the service to the device, ready to call the client
Client
Create a new Android application project, named Playerclient. Direct copy to Customer of package with Aidl file on service side
In the end src directory, keep the aidl files in the package, and other deletions.
Write Mainactivity.java code as follows
Copy Code code as follows:

/**
* Client Control Interface
*/
public class Mainactivity extends activity {

public static final String TAG = "mainactivity";

String of Intent-filter action declarations in service-side androidmanifest.xml
public static final String ACTION = "Com.example.playerserver.PlayerService";

Private Button playbtn, stopbtn;

Private Iremoteservice Mservice;

Private Boolean isbinded = false;

Private Serviceconnection conn = new Serviceconnection () {

@Override
public void onservicedisconnected (componentname name) {
isbinded = false;
Mservice = null;
}

@Override
public void onserviceconnected (componentname name, IBinder service) {
Mservice = IRemoteService.Stub.asInterface (service);
Isbinded = true;
}
};
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Dobind ();
Initviews ();
}
private void Initviews () {
PLAYBTN = (Button) Findviewbyid (R.id.button1);
STOPBTN = (Button) Findviewbyid (R.id.button2);
Playbtn.setonclicklistener (Clicklistener);
Stopbtn.setonclicklistener (Clicklistener);
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Getmenuinflater (). Inflate (R.menu.activity_main, menu);
return true;
}
@Override
protected void OnDestroy () {
Dounbind ();
Super.ondestroy ();
}
public void Dobind () {
Intent Intent = new Intent (ACTION);
Bindservice (Intent, Conn, context.bind_auto_create);
}
public void Dounbind () {
if (isbinded) {
Unbindservice (conn);
Mservice = null;
isbinded = false;
}

}
Private Onclicklistener Clicklistener = new Onclicklistener () {

@Override
public void OnClick (View v) {
if (v.getid () = = Playbtn.getid ()) {
Play
LOG.I (TAG, "play button clicked");
try {
Mservice.play ();
catch (RemoteException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
} else {
Stop
LOG.I (TAG, "stop button clicked");
try {
Mservice.stop ();
catch (RemoteException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
};
}

Mainactivity is automatically generated from the wizard and does not need to be registered in Androidmanifest.xml
Run client to device, press button to play/stop effect as shown

If you want to study more detailed implementation principles, see this article:
Http://www.cnblogs.com/over140/archive/2011/03/08/1976890.html

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.