Android Service (iii) -- bindservice and remoteservice

Source: Internet
Author: User
Tags call back

I. Introduction to bindservice

Bindservice is a binding service that executes the logical process in the service.

The service starts using the context. startservice () method and stops using the context. stopservice () method. You can also stop yourself using the service. stopself () method or service. stopselfresult () method. You can stop the service by calling the stopservice () method once, no matter how many times it was called before.

 

The client establishes a connection with the service and uses this link to communicate with the service. The service is bound using the context. bindservice () method, and the context. unbindservice () method is used to close the service. Multiple Clients can bind the same service. If the service is not started, bindservice () can start the service.

 

The above startservice () and bindservice () modes are completely independent. You can bind a service that has been started using the startservice () method. For example, a background playing music service can use a startservice (intend) object to play music. You may need to perform some operations during Playing, such as obtaining information about a song. In this case, the activity can establish a connection with the service by calling the bindservices () method. In this case, the stopservices () method does not actually stop the service until the last binding is closed.

Ii. bindservice Startup Process

Context. bindservice ()-> oncreate ()-> onbind ()-> Service Running-> onunbind ()-> ondestroy ()-> service stop
 

Onbind () returns an ibind interface instance to the client. ibind allows the client to call back the service methods, such as obtaining the service instance, running status, or other operations. At this time, the caller (such as activity) will be bound with the service, and the context will exit, and srevice will call onunbind-> ondestroy to exit accordingly.

Therefore, the life cycle of calling bindservice is oncreate --> onbind (only once, cannot be bound multiple times) --> onunbind --> ondestory.

During each service enabling and disabling process, only onstart can be called multiple times (through multiple startservice calls), other oncreate, onbind, onunbind, ondestory can only be called once in a lifecycle. For details, see Android Service (1) -- service.

Iii. bindservice Lifecycle

Like an activity, a service can be used to change the state of the lifecycle method, but less than the activity method, the service life cycle method has only three public

Void oncreate ()

Void onstart (intent)

Void ondestroy ()

By implementing these three lifecycle methods, You can monitor the lifecycle of two nested loops of the Service:

1. Entire Lifecycle

The entire service lifecycle is between the oncreate () and ondestroy () methods. Like activity, it is initialized in the oncreate () method and released in the ondestroy () method. For example, a background music playing service can be played in the oncreate () method and stopped in the ondestroy () method.

 

2. Activity Lifecycle

The active life cycle of the service is after onstart (). This method will process intent objects passed through the startservices () method. The music service can open an intent object to find the music to play and start playing it in the background. Note: There is no corresponding callback method when the service is stopped, that is, there is no onstop () method.

 

The oncreate () method and ondestroy () method are for all services. Whether or not they are started, they can be accessed and executed through the context. startservice () and context. bindservice () methods. However, the onstart () method is called only when the service is started using the startservice () method.

 

If a service allows binding by others, you need to implement the following additional methods:

Ibinder onbind (intent)

Boolean onunbind (intent)

Void onrebind (intent)

The onbind () callback method will continue to pass the intent object passed through bindservice ().

Onunbind () processes the intent object passed to unbindservice. If the service allows binding, onbind () will return the communication handle (Instance) that the client and the service communicate with each other ).

If a new client and service connection are established, the onunbind () method can call the onrebind () method.

Remember any service, no matter how it is established, the client can be linked by default, so any service can receive the onbind () and onunbind () Methods

Iv. bindservice example

Activity

Public class playbindmusic extends activity implements onclicklistener {</P> <p> private button playbtn; <br/> private button stopbtn; <br/> private button pausebtn; <br/> private button exitbtn; </P> <p> private bindmusicservice musicservice; </P> <p> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); </P> <p> setcontentview (R. layout. bind_music_service); </P> <P> playbtn = (button) findviewbyid (R. id. play); <br/> stopbtn = (button) findviewbyid (R. id. stop); <br/> pausebtn = (button) findviewbyid (R. id. pause); <br/> exitbtn = (button) findviewbyid (R. id. exit); </P> <p> playbtn. setonclicklistener (this); <br/> stopbtn. setonclicklistener (this); <br/> pausebtn. setonclicklistener (this); <br/> exitbtn. setonclicklistener (this); </P> <p> connection (); <br/>}</P> <p> private void Connection () {<br/> intent = new intent ("com. homer. BIND. bindservice "); <br/> bindservice (intent, SC, context. bind_auto_create); // bindservice <br/>}</P> <p> @ override <br/> Public void onclick (view v) {<br/> switch (v. GETID () {<br/> case R. id. play: <br/> musicservice. play (); <br/> break; <br/> case R. id. stop: <br/> If (musicservice! = NULL) {<br/> musicservice. stop (); <br/>}< br/> break; <br/> case R. id. pause: <br/> If (musicservice! = NULL) {<br/> musicservice. pause (); <br/>}< br/> break; <br/> case R. id. exit: <br/> This. finish (); <br/> break; <br/>}</P> <p> private serviceconnection SC = new serviceconnection () {</P> <p> @ override <br/> Public void onserviceconnected (componentname, ibinder Service) {// Connect service <br/> musicservice = (bindmusicservice. mybinder) (Service )). getservice (); <br/> If (musicservice! = NULL) {<br/> musicservice. play (); // play music <br/>}</P> <p> @ override <br/> Public void onservicedisconnected (componentname name) {// disconnect service <br/> musicservice = NULL; <br/>}< br/> }; </P> <p> @ override <br/> Public void ondestroy () {<br/> super. ondestroy (); </P> <p> If (SC! = NULL) {<br/> unbindservice (SC); <br/>}< br/>}
Service

Public class bindmusicservice extends Service {</P> <p> private mediaplayer; </P> <p> private final ibinder binder = new mybinder (); </P> <p> public class mybinder extends binder {<br/> bindmusicservice getservice () {<br/> return bindmusicservice. this; <br/>}</P> <p> @ override <br/> Public ibinder onbind (intent) {<br/> return binder; <br/>}</P> <p> @ override <br/> Public void oncreate () {<Br/> super. oncreate (); </P> <p> toast. maketext (this, "Show Media Player", toast. length_short ). show (); <br/>}</P> <p> @ override <br/> Public void ondestroy () {<br/> super. ondestroy (); </P> <p> toast. maketext (this, "Stop Media Player", toast. length_short); <br/> If (mediaplayer! = NULL) {<br/> mediaplayer. stop (); <br/> mediaplayer. release (); <br/>}</P> <p> Public void play () {<br/> If (mediaplayer = NULL) {<br/> mediaplayer = mediaplayer. create (this, R. raw. TMP); <br/> mediaplayer. setlooping (false); <br/>}< br/> If (! Mediaplayer. isplaying () {<br/> mediaplayer. start (); <br/>}</P> <p> Public void pause () {<br/> If (mediaplayer! = NULL & mediaplayer. isplaying () {<br/> mediaplayer. pause (); <br/>}</P> <p> Public void stop () {<br/> If (mediaplayer! = NULL) {<br/> mediaplayer. stop (); <br/> try {<br/> mediaplayer. prepare (); // call the prepare function <br/>} catch (ioexception ex) {<br/> ex. printstacktrace (); <br/>}< br/>}
Androidmanifest. xml

<Service <br/> Android: Name = ". BIND. bindmusicservice "<br/> Android: enabled =" true "> <br/> <intent-filter> <br/> <action Android: Name =" com. homer. BIND. bindservice "/> <br/> </intent-filter> <br/> </service>

V. Code Parsing

1. Intent intent = new intent ("com. homer. BIND. bindservice "); construct a service action, and then bindservice (intent, SC, context. bind_auto_create); bind the service

2. In activity, a service connection is established through private serviceconnection SC = new serviceconnection (), onserviceconnected () gets the service instance, and onservicedisconnected () releases the connection.

3. In Service, reload the onbind (intent) method, return the service instance (that is, bindmusicservice) to the activity, and then execute the oncreate () function (Note: bindservice does not execute the onstart () function)

4. In the activity, the returned service instance musicservice is used to play the music (play, pause, stop, etc)

Vi. remote service expansion

Generally, each application runs in its own process, but sometimes it needs to pass objects (IPC communication) between processes ), you can use the application UI to write a service that runs in a different process. On the Android platform, a process generally cannot access the memory area of other processes. Therefore, they need to split objects into simple forms that the operating system can understand, so as to disguise them as cross-border access. Writing this disguised code is rather boring. Fortunately, Android provides an aidl tool for us to do this.
 
Aidl(Android Interface Description Language) is an IDL Language that generates a piece of code that allows two processes running on an Android device to interact with each other using internal communication processes. If you need to access a method of an object in another process (for example, in an activity) (for example, a service) in another process, you can use aidl to generate such code to pass various parameters in disguise.
 
To use aidl, the Service must provide the service interface in the form of an aidl file. The aidl tool will generate a corresponding Java interface, in addition, the generated Service Interface contains a function-called stub service pile class. The service implementation class must inherit the stub service pile class. The onbind method of the Service will return the object of the implementation class, and then you can use it. See the following example:

Imusiccontrolservice. aidl

Package COM. homer. remote; </P> <p> interface imusiccontrolservice {<br/> void play (); <br/> void stop (); <br/> void pause (); <br/>}Using the android plug-in of Eclipse, a Java interface class is generated based on the aidl file. The generated interface class contains an internal class stub class, and the service inherits the stub class:ServicePublic class remotemusicservice extends Service {</P> <p> private mediaplayer; </P> <p> @ override <br/> Public ibinder onbind (intent) {<br/> return binder; <br/>}</P> <p> private final imusiccontrolservice. stub binder = new imusiccontrolservice. stub () {</P> <p> @ override <br/> Public void play () throws RemoteException {<br/> If (mediaplayer = NULL) {<br/> mediaplayer = mediaplayer. create (R Emotemusicservice. This, R. Raw. tmp); <br/> mediaplayer. setlooping (false); <br/>}< br/> If (! Mediaplayer. isplaying () {<br/> mediaplayer. start (); <br/>}</P> <p> @ override <br/> Public void pause () throws RemoteException {<br/> If (mediaplayer! = NULL & mediaplayer. isplaying () {<br/> mediaplayer. pause (); <br/>}</P> <p> @ override <br/> Public void stop () throws RemoteException {<br/> If (mediaplayer! = NULL) {<br/> mediaplayer. stop (); <br/> try {<br/> mediaplayer. prepare (); // call the prepare function <br/>} catch (ioexception ex) {<br/> ex. printstacktrace (); <br/>}< br/> }; </P> <p> @ override <br/> Public void ondestroy () {<br/> super. ondestroy (); </P> <p> If (mediaplayer! = NULL) {<br/> mediaplayer. Stop (); <br/> mediaplayer. Release (); <br/>}< br/>}
When the client (activity) Application connects to this service, the onserviceconnected method will be called, and the client will be able to obtain the ibinder object. See the onserviceconnected method of the client below:

Activity

Public class playremotemusic extends activity implements onclicklistener {</P> <p> private button playbtn; <br/> private button stopbtn; <br/> private button pausebtn; <br/> private button exitbtn; </P> <p> private imusiccontrolservice musicservice; </P> <p> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. remote_music_servi CE); </P> <p> playbtn = (button) findviewbyid (R. id. play); <br/> stopbtn = (button) findviewbyid (R. id. stop); <br/> pausebtn = (button) findviewbyid (R. id. pause); <br/> exitbtn = (button) findviewbyid (R. id. exit); </P> <p> playbtn. setonclicklistener (this); <br/> stopbtn. setonclicklistener (this); <br/> pausebtn. setonclicklistener (this); <br/> exitbtn. setonclicklistener (this); </P> <p> connection (); <br/>}</P> <p> priva Te void connection () {<br/> intent = new intent ("com. homer. remote. remotemusicreceiver "); <br/> bindservice (intent, SC, context. bind_auto_create); // bindservice <br/>}</P> <p> @ override <br/> Public void onclick (view V) {</P> <p> try {<br/> switch (v. GETID () {<br/> case R. id. play: <br/> musicservice. play (); <br/> break; <br/> case R. id. stop: <br/> If (musicservice! = NULL) {<br/> musicservice. stop (); <br/>}< br/> break; <br/> case R. id. pause: <br/> If (musicservice! = NULL) {<br/> musicservice. pause (); <br/>}< br/> break; <br/> case R. id. exit: <br/> This. finish (); <br/> break; <br/>}< br/>} catch (RemoteException e) {<br/> E. printstacktrace (); <br/>}</P> <p> private serviceconnection SC = new serviceconnection () {<br/> @ override <br/> Public void onserviceconnected (componentname, ibinder Service) {// Connect service <br/> musicservice = imusiccontrolservice. Stub. asinterface (service); <br/>}</P> <p> @ override <br/> Public void onservicedisconnected (componentname name) {// disconnect service <br/> musicservice = NULL; <br/>}</P> <p> }; </P> <p> @ override <br/> Public void ondestroy () {<br/> super. ondestroy (); </P> <p> If (SC! = NULL) {<br/> unbindservice (SC); // unbindservice <br/>}< br/>}
Remote service process summary:

1. In activity (client), intent = new intent ("com. homer. remote. remotemusicreceiver "); construct the intent, and then bindservice (intent, SC, context. bind_auto_create); bind the service

2. In activity (client), reload onserviceconnected () through serviceconnection () to establish a connection and obtain the service. Stub instance; onservicedisconnected () to release the connection (similar to bindservice)

3. In the service, the onbind (intent) is reloaded to return the service. stub instance, but service. the stub class is an internal class of the Interface Class generated by the aidl file. The service inherits the stub class.

4. In an activity, you can use the service instance (musicservice) to play music (play, pause, stop, and so on)

Source code download

Reference recommendations:

Service (Android Developer)

Android Service (1) -- service

Android Service (II) -- broadcastreceiver

Service and aidl in Android

Android service aidl

Android notes-service and aidl

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.