Service in Android

Source: Internet
Author: User

The service runs in the background for a period of time and does not interact with the application components. Each service must be declared in manifest through <service>. It can be started through contect. startservice and contect. bindserverice.
Like other application components, the service runs in the main process. This means that if the service requires a lot of time-consuming or congested operations, it needs to be implemented in its subthread.

Two Service Modes


The local service is used inside the application.
It can be started and run until someone stops it or it stops it. In this way, it starts by calling context. startservice () and ends by calling context. stopservice. It can call service. stopself () or service. stopselfresult () to stop itself. No matter how many times the startservice () method is called, you only need to call stopservice () once to stop the service.

It is used to implement some time-consuming tasks of the application itself, such as querying the upgrade information. It does not occupy the application, such as the thread to which the activity belongs, but is executed in the single-thread background, so that the user experience is better.


Remote service is used between applications in the Android system.
It can perform program operations through APIS defined and exposed by itself. The client establishes a connection to the service object and calls the service through that connection. Connection to call the context. bindservice () method to establish, to call context. unbindservice () to close. Multiple clients can be bound to the same service. If the service is not loaded yet, bindservice () loads it first.
It can be reused by other applications, such as the weather forecast service. Other applications do not need to write such services and can call existing services.
Startservice ()/bindservice () is not completely isolated.

Lifecycle
The service lifecycle is not as complex as the activity. It only inherits the oncreate (), onstart (), and ondestroy () methods. When we start the service for the first time, the oncreate () and onstart () methods are called successively. when the service is stopped, the ondestroy () method is executed. Note that if the service has been started, when we start the service again, we will not execute the oncreate () method, but directly execute the onstart () method.

Difference between startservice and bindservice
1. Use the startservice () method to enable the service. There is no relation between the caller and the service. Even if the caller exits, the Service continues to run.
If you plan to use the context. startservice () method to start the service, when the service is not created, the system will first call the oncreate () method of the service and then call the onstart () method.
If the service has been created before the startservice () method is called, multiple call of the startservice () method will not lead to multiple creation of the service, but will lead to multiple calls of the onstart () method.
A service started using the startservice () method can only end the service by calling the context. stopservice () method. The ondestroy () method is called when the service ends.

2. Use the bindservice () method to enable the Service. The caller and the service are bound together. Once the caller exits, the service is terminated. This feature has the following features: "The caller does not want to generate at the same time and must die at the same time.
Onbind () calls back this method only when the context. bindservice () method is used to start the service. This method is called when the caller binds to the service. When the caller and the service are already bound, multiple calls to the context. bindservice () method will not cause this method to be called multiple times.
When the context. bindservice () method is used to start a service, only the onunbind () method can be called to release the caller and the service. When the service ends, the ondestroy () method is called.

Example of using service to play music

First look at the final result


Code List:

Layout File

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> <textview Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "Welcome to my blog! "Android: textsize =" 16sp "/> <textview Android: layout_width =" fill_parent "Android: layout_height =" wrap_content "Android: TEXT = "music playback service"/> <button Android: Id = "@ + ID/startmusic" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: TEXT = "enable music playback service"/> <button Android: Id = "@ + ID/stopmusic" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: TEXT = "Stop playing music"/> <button Android: Id = "@ + ID/bindmusic" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: TEXT = "bind music player service"/> <button Android: Id = "@ + ID/unbindmusic" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: TEXT = "Unbind -- bind music play service"/> </linearlayout>

Musicservice

Package COM. example. musicservice; import android. app. service; import android. content. intent; import android. media. mediaplayer; import android. OS. ibinder; import android. util. log; import android. widget. toast; public class musicservice extends Service {// set the label Private Static string tag = "musicservice" for the log tool; // define the music player variable private mediaplayer mplayer; // this method is called when the service does not exist and needs to be created. This method is called no matter startservice () or bindservice (). @ override public void oncreate () {toast. maketext (this, "musicsevice oncreate ()", toast. length_short ). show (); log. E (TAG, "musicserice oncreate ()"); mplayer = mediaplayer. create (getapplicationcontext (), R. raw. music); // you can set to play the mplayer repeatedly. setlooping (true); super. oncreate () ;}@ override public void onstart (intent, int startid) {toast. maketext (this, "musicsevice onstart ()", toast. length_short ). show (); log. E (TAG, "musicserice onstart ()"); mplayer. start (); super. onstart (intent, startid) ;}@ override public void ondestroy () {toast. maketext (this, "musicsevice ondestroy ()", toast. length_short ). show (); log. E (TAG, "musicserice ondestroy ()"); mplayer. stop (); super. ondestroy ();} // when other objects use the bindservice method to notify the service, this method is called @ override public ibinder onbind (intent) {toast. maketext (this, "musicsevice onbind ()", toast. length_short ). show (); log. E (TAG, "musicserice onbind ()"); mplayer. start (); return NULL;} // when other objects use the unbindservice method to notify the service, this method is called @ override public Boolean onunbind (intent) {toast. maketext (this, "musicsevice onunbind ()", toast. length_short ). show (); log. E (TAG, "musicserice onunbind ()"); mplayer. stop (); return Super. onunbind (intent );}}

Mainactivy (call service)

Package COM. example. musicservice; import android. app. activity; import android. content. componentname; import android. content. context; import android. content. intent; import android. content. serviceconnection; import android. OS. bundle; import android. OS. ibinder; import android. util. log; import android. view. view; import android. widget. button; import android. widget. toast; import android. view. view. onclicklistener; public class mainactivity extends activity {// set the label Private Static string tag = "musicservice" for the log tool;/** called when the activity is first created. * // @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); // outputs toast messages and logs toast. maketext (this, "musicserviceactivity", toast. length_short ). show (); log. E (TAG, "musicserviceactivity"); initlizeviews ();} private void initlizeviews () {button btnstart = (button) findviewbyid (R. id. startmusic); button btnstop = (button) findviewbyid (R. id. stopmusic); button btnbind = (button) findviewbyid (R. id. bindmusic); button btnunbind = (button) findviewbyid (R. id. unbindmusic); // defines the click listener onclicklistener OCL = new onclicklistener () {@ override public void onclick (view V) {// display the object specified by the specified intent is a service intent = new intent (mainactivity. this, musicservice. class); Switch (v. GETID () {case R. id. startmusic: // start the service startservice (intent); break; case R. id. stopmusic: // stop the service stopservice (intent); break; case R. id. bindmusic: // bindservice (intent, Conn, context. bind_auto_create); break; case R. id. unbindmusic: // unbindservice (conn); break ;}}; // click to listen for btnstart. setonclicklistener (OCl); btnstop. setonclicklistener (OCl); btnbind. setonclicklistener (OCl); btnunbind. setonclicklistener (OCl);} // defines the final serviceconnection conn = new serviceconnection () {@ override public void onservicedisconnected (componentname name) {toast. maketext (mainactivity. this, "musicserviceactivity onsevicedisconnected", toast. length_short ). show (); log. E (TAG, "musicserviceactivity onsevicedisconnected") ;}@ override public void onserviceconnected (componentname, ibinder Service) {toast. maketext (mainactivity. this, "musicserviceactivity onserviceconnected", toast. length_short ). show (); log. E (TAG, "musicserviceactivity onserviceconnected ");}};}

The final result is:

When you press the first button, use the startservice () method to enable the Service. Even if you exit the activity, the service is still there and the concert continues to play. View the program running status:



If you use the bindservice () method to enable the Service, the caller and the service are bound together. When you exit activy, the service is stopped.

With startservice (), we can release activty resources after exiting the program. Because the service is still running in the background, our music can continue to be played ,. In this way, we can enjoy music, chat QQ, or browse news and so on.


Refer:

Android
Service Usage-simple music play instance-http://blog.csdn.net/cjjky/article/details/6552852

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.