Android service Introduction II aidl

Source: Internet
Author: User

First, describe the content we want to implement. We hope to click the button in one application to operate the music playing Function Applied in another process.

When we click "play", the system will remotely call a service provided by US (not the same as the current service), and then operate the music playing in the service, click "stop" to terminate the playback. To replay a video, you must first click "Destroy service" and then click the play button. (Why do I need to click the destroy button to play the video? It is to show you how to unbind the service when a service is called remotely ).

 

In this example, we use aidl, a very important concept.

The description language of the android Interface Definition Language (aidl) is used to allow communication between different processes.

We all know that each application runs in its own process, and the Android platform does not allow direct object data transmission between different processes. If we need to communicate between processes, we must break down our data objects into tiny data units that can be understood by the operating system, then it passes the process boundary check in an orderly manner.

If we can implement it by ourselves, we will all die with a batch of programmers. Fortunately, Android solved this problem for us, which is why aidl emerged.

Aidl (Android Interface Definition Language) is an IDL Language used to generate code for inter-process communication (IPC) between two processes on the Android device. If you want to call operations on objects in another process (such as service) in a process (such as activity), you can use aidl to generate serializable parameters.
The aidl IPC Mechanism is interface-oriented, like com or CORBA, but more lightweight. It uses a proxy class to transmit data on the client and the implementation end.

 

Note: aidl only supports methods, does not define static members, and methods cannot have modifiers similar to public. aidl running methods have any type of parameters and return values, in Java, the following types do not need to be imported, including basic data types, String, map, and list. to avoid errors, we recommend that you import the package as long as you use it.

-------------------------------------------------------------------------------

Steps for using aidl:

 

Server (providing services ):

Step 1: Define a *. aidl file, which is an interface definition conforming to the aidl language specification, which defines the methods that external applications can access. When we save this file, eclipse will automatically generate a corresponding Java interface file for us in the gen folder. For example, remoteserviceinterface. Java

 

Step 2: Define a service and register it to the androidmanifest. xml file. For example:

<Service android: Name = "myremoteservice">
<Intent-filter>
<Action Android: Name = "cn.com. chenzheng_java.remote"/>
</Intent-filter>
</Service>

Note that an intent-filter must be provided here. Our client process accesses the server process through this action.

We all know that when implementing our own service, we must implement the onbind () method in service for other applications to interact with our service through bindservice, and return an internal class that inherits the binder. Here, eclipse automatically generates the remoteserviceinterface for us. in Java, there is an internal class that implements the binder, remoteserviceinterface. stub. Aidl requires that we cannot directly implement the binder class here, but implement it. aidl provides stub class to us. While implementing the stub class, aidl also requires us to implement the specific implementation of various services defined in the interface at the same time. So far, our server has been bound with our aidl file.

 

Client:

 

Step 1: If the client wants to use this service, it must first know what services our service actually provides in the aidl file, right? Therefore, the first step is to copy the aidl file to the client program. (Note that the package path must be consistent with that on the server, for example, the server is cn.com. chenzheng_java.remote.a.aidl, this path should also be used on the client side ).

 

Step 2: we all know that to interact with the service, we need to use the bindservice method, which has a serviceconnection type parameter. Our main code is in the implementation of this interface.

 

Step 3: Use remoteserviceinterface = remoteserviceinterface in the onserviceconnected (componentname, ibinder Service) method of serviceconnection implementation class. stub. asinterface (service); method to obtain the instance of the service provided by the remote server, then we can use the method provided in the remoteserviceinterface object to call the interface for interaction. (The key here is to use *. stub. asinterface (service); To obtain an aidl interface instance)

 

As we mentioned earlier on the server, an intent-filter must be provided to match the request validity. Therefore, when the client accesses the service, it must also pass the intent that matches the action.

Bytes --------------------------------------------------------------------------------------

The Code is as follows:

 

 

 

 

 

 

 

 

Remote Server:

Remoteserviceinterface. aidl

Package cn.com. chenzheng_java.remote; <br/>/** the syntax of aidl is slightly different from that of interface. <br/> * It can only contain methods, and the modifiers such as public in Java are not supported here. <br/> * When we add. if your aidl file ends with aidl is in the correct format, <br/> * in the gen directory, you will see the corresponding Java class automatically generated by the system based on the aidl file you provide <br/> * @ author chenzheng_java <br/> */</P> <p> Interface remoteserviceinterface {</P> <p> void startmusic (); <br/> void stopmusic (); <br/>}< br/>

Myremoteservice. Java

Package cn.com. chenzheng_java.remote; </P> <p> Import Java. io. ioexception; </P> <p> Import android. app. service; <br/> Import android. content. intent; <br/> Import android. media. mediaplayer; <br/> Import android. OS. ibinder; <br/> Import android. OS. remoteException; <br/>/** <br/> * @ description remote service <br/> * @ author chenzheng_java <br/> */<br/> Public class myremoteservice extends Service {<br/> med Iaplayer mediaplayer; <br/> @ override <br/> Public ibinder onbind (intent) {<br/> return New mybinder (); <br/>}< br/> @ override <br/> Public void oncreate () {<br/>/* <br/> * mediaplayer. the first parameter of the create method is actually the context object. Here we pass the service directly to it, <br/> * because the service itself inherits the context. <Br/> */<br/> mediaplayer = mediaplayer. create (myremoteservice. this, R. raw. aiweier); <br/> super. oncreate (); <br/>}</P> <p>/** <br/> * @ description note that binder is not inherited, instead, the system automatically generates <br/> * an internal class of the binder, called stub. By inheriting the stub class and implementing the methods defined in aidl <br/> *, we implement the methods of the interface. <Br/> * @ author chenzheng_java <br/> */<br/> private class mybinder extends remoteserviceinterface. stub {</P> <p> Public void startmusic () throws RemoteException {</P> <p> mediaplayer. start (); </P> <p >}</P> <p> Public void stopmusic () throws RemoteException {<br/> mediaplayer. stop (); <br/> try {<br/> mediaplayer. prepare (); <br/>} catch (illegalstateexception e) {<br/> E. printstacktrace (); <br/>}catch (ioexception e) {<br/> E. printstacktrace (); <br/>}</P> <p >}< br/>

Remoteserviceactivity. Java

Package cn.com. chenzheng_java.remote; </P> <p> Import android. app. activity; <br/> Import android. OS. bundle; <br/>/** <br/> * many people do not understand it. Basically nothing is implemented here. Why? <Br/> * In fact, this is the reason. We have finished writing the service code and registered it in the configuration file. <br/> * Will the mobile phone system recognize it? No. You must run the <br/> * application of the Service at least once. How do you know that you have added a service on your phone! <Br/> * @ author chenzheng_java <br/> */<br/> public class remoteserviceactivity extends activity {<br/> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); <br/>}< br/>}

Androidmanifest. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <manifest xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> package = "cn.com. chenzheng_java.remote "<br/> Android: versioncode =" 1 "<br/> Android: versionname =" 1.0 "> <br/> <uses-SDK Android: minsdkversion = "8"/> </P> <p> <application Android: icon = "@ drawable/icon" Android: label = "@ string/app_name"> <br/> <activity Android: Name = ". remoteserviceactivity "<br/> Android: Label =" @ string/app_name "> <br/> <intent-filter> <br/> <action Android: Name =" android. intent. action. main "/> <br/> <category Android: Name =" android. intent. category. launcher "/> <br/> </intent-filter> <br/> </activity> </P> <p> <service android: name = "myremoteservice"> <br/> <intent-filter> <br/> <action Android: Name = "cn.com. chenzheng_java.remote "/> <br/> </intent-filter> <br/> </service> </P> <p> </Application> <br/> </manifest>

Client:

Activity Code:

Package cn.com. chenzheng_java; </P> <p> Import android. app. activity; <br/> Import android. content. componentname; <br/> Import android. content. context; <br/> Import android. content. intent; <br/> Import android. content. serviceconnection; <br/> Import android. OS. bundle; <br/> Import android. OS. ibinder; <br/> Import android. OS. remoteException; <br/> Import android. util. log; <br/> Import android. view. view; <br/> Import android. view. view. onclicklistener; <br/> Import android. widget. button; <br/> Import cn.com. chenzheng_java.remote.remoteserviceinterface; <br/>/*** <br/> * @ author chenzheng_java <br/> * @ description call remote services in different processes through the current activity <br/> */< br/> public class localserviceactivity extends activity implements onclicklistener {<br/> string action_name = "cn.com. chenzheng_java.remote "; <br/> Boolean flag = false; <br/> button button_start; <br/> button button_stop; <br/> button button_destroy; </P> <p> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. music); </P> <p> button_start = (button) findviewbyid (R. id. button1); <br/> button_stop = (button) findviewbyid (R. id. button2); <br/> button_destroy = (button) findviewbyid (R. id. button3); </P> <p> button_start.setonclicklistener (this); <br/> button_stop.setonclicklistener (this); <br/> button_destroy.setonclicklistener (this ); <br/>}</P> <p> remoteserviceinterface; </P> <p> private class myserviceconnection implements serviceconnection {<br/> Public void onserviceconnected (componentname, ibinder Service) {<br/> remoteserviceinterface = remoteserviceinterface. stub. asinterface (service); <br/> try {<br/> log. I ("flag", flag + ""); <br/> If (FLAG) {<br/> log. I ("notice", "singing started"); <br/> remoteserviceinterface. startmusic (); <br/>}else {<br/> log. I ("notice", "singing stopped"); <br/> remoteserviceinterface. stopmusic (); <br/>}</P> <p >}catch (RemoteException e) {<br/> E. printstacktrace (); <br/>}</P> <p> Public void onservicedisconnected (componentname name) {</P> <p >}</P> <p> private myserviceconnection serviceconnection = new myserviceconnection (); </P> <p> Public void onclick (view v) {<br/> If (V = button_start) {<br/> flag = true; <br/> intent = new intent (action_name); <br/>/** <br/> * context. bind_auto_create when binding service, if you find that you have not created one, create one first, and then bind <br/> */<br/> bindservice (intent, serviceconnection, context. bind_auto_create); <br/>}</P> <p> If (V = button_stop) {<br/> log. I ("notification", "the stop button has been clicked"); <br/> flag = false; <br/> intent = new intent (action_name ); <br/> bindservice (intent, serviceconnection, context. bind_auto_create); <br/> try {<br/> remoteserviceinterface. stopmusic (); <br/>}catch (RemoteException e) {<br/> E. printstacktrace (); <br/>}</P> <p> If (V = button_destroy) {<br/> flag = false; <br/> intent = new intent (action_name); <br/> bindservice (intent, serviceconnection, context. bind_auto_create); <br/> unbindservice (serviceconnection); <br/>}</P> <p >}< br/>}

Music. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: layout_width = "match_parent" Android: layout_height = "match_parent"> <br/> <button Android: TEXT = "play" Android: Id = "@ + ID/button1" <br/> Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"> </button> <br/> <button Android: text = "stop" Android: Id = "@ + ID/button2" <br/> Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"> </button> <br/> <button Android: text = "Destroy service" Android: id = "@ + ID/button3" <br/> Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"> </button> <br/> </linearlayout> <br/>

Other codes that are not pasted are generated by default.


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.