Android Service (1) -- service

Source: Internet
Author: User
Tags exit in

1. Service Introduction

A service is one of the four main components in the Android system (activity, service, broadcastreceiver, and contentprovider). It is similar to the activity level, but cannot run on its own and can only run on the background, and can interact with other components. The service can be used in multiple applications. For example, when the user starts other activities during multimedia playback, the program must continue playing the video in the background, for example, detecting file changes on the SD card, or record the changes in your location in the background. In short, the service is always stored in the background.

There are two ways to start a service:Context. startservice ()AndContext. bindservice ()


2. Service start Process

Context. startservice () Startup Process:


Context. startservice ()-> oncreate ()-> onstart ()-> Service Running-> context. stopservice ()-> ondestroy ()-> service stop

If the service is not running, Android calls oncreate () and then onstart ();

If the service is already running, only onstart () is called. Therefore, the onstart method of a service may be called multiple times.

If the stopservice is called ondestroy directly, if the caller directly exits without calling the stopservice, the Service will continue to run in the background. After the service is started, the caller can use the stopservice to disable the service.

Therefore, the life cycle for calling startservice is oncreate --> onstart (which can be called multiple times) --> ondestroy


Context. 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.

 

3. Service Lifecycle

The lifecycle of a service is not as complex as that of an activity. It only inherits three methods: oncreate (), onstart (), and ondestroy ().

When we start the service for the first time, we call the oncreate () and onstart () Methods 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, the oncreate () method is not executed, but the onstart () method is directly executed.

It can use service. stopself () method or service. the stopselfresult () method is used to stop a service. You only need to call the stopservice () method once to stop the service, no matter how many times you call the start service method.

4. Service example

Below I made a simple music playing application, using startservice and bindservice to start local services respectively.

Activity

Public class playmusicservice extends activity implements onclicklistener {</P> <p> private button playbtn; <br/> private button stopbtn; <br/> private button pausebtn; <br/> private button exitbtn; <br/> private button closebtn; </P> <p> private intent; </P> <p> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. music_s Ervice); </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); <br/> closebtn = (button) findviewbyid (R. id. close); </P> <p> playbtn. setonclicklistener (this); <br/> stopbtn. setonclicklistener (this); <br/> pausebtn. setonclicklistener (this); <br/> exitbtn. setonclic Klistener (this); <br/> closebtn. setonclicklistener (this); </P> <p >}</P> <p> @ override <br/> Public void onclick (view V) {<br/> int op =-1; <br/> intent = new intent ("com. homer. service. musicservice "); </P> <p> switch (v. GETID () {<br/> case R. id. play: // play music <br/> op = 1; <br/> break; <br/> case R. id. stop: // stop music <br/> op = 2; <br/> break; <br/> case R. id. pause: // pause music <br/> op = 3; <br/> break; <Br/> case R. id. close: // close activity <br/> This. finish (); <br/> break; <br/> case R. id. exit: // stopservice <br/> op = 4; <br/> stopservice (intent); <br/> This. finish (); <br/> break; <br/>}</P> <p> bundle = new bundle (); <br/> bundle. putint ("op", OP); <br/> intent. putextras (bundle); </P> <p> startservice (intent ); // startservice <br/>}</P> <p> @ override <br/> Public void ondestroy () {<br/> super. ondestroy (); </P> <p> If (intent! = NULL) {<br/> stopservice (intent); <br/>}< br/>}

Service

Public class musicservice extends Service {<br/> Private Static final string tag = "myservice"; </P> <p> private mediaplayer; </P> <p> @ override <br/> Public ibinder onbind (intent arg0) {<br/> return NULL; <br/>}</P> <p> @ override <br/> Public void oncreate () {<br/> log. V (TAG, "oncreate"); <br/> toast. maketext (this, "Show Media Player", toast. length_short ). show (); </P> <p> If (mediaplayer = NULL) {< Br/> mediaplayer = mediaplayer. create (this, R. raw. TMP); <br/> mediaplayer. setlooping (false); <br/>}</P> <p> @ override <br/> Public void ondestroy () {<br/> log. V (TAG, "ondestroy"); <br/> toast. maketext (this, "Stop Media Player", toast. length_short); <br/> If (mediaplayer! = NULL) {<br/> mediaplayer. stop (); <br/> mediaplayer. release (); <br/>}</P> <p> @ override <br/> Public void onstart (intent, int startid) {<br/> log. V (TAG, "onstart"); <br/> If (intent! = NULL) {<br/> bundle = intent. getextras (); <br/> If (bundle! = NULL) {<br/> int op = bundle. getint ("op"); <br/> switch (OP) {<br/> case 1: <br/> play (); <br/> break; <br/> case 2: <br/> stop (); <br/> break; <br/> case 3: <br/> pause (); <br/> break; <br/>}</P> <p> Public void play () {<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

Register Activity

<Activity <br/> Android: Name = ". Service. playmusicservice" <br/> Android: Label = "@ string/app_name"/>

Register Service

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

V. Code Parsing

1. In the activity, playmusicservice uses the onclicklistener interface onclick () method to control the playing of music, and transmits various music operations to the service using a number through intent.

Construct an intent, intent = new intent ("com. Homer. Service. musicservice ");

Among them, Com. Homer. Service. musicservice is the definition of service in androidmanifest. XML, that is, the above "Register Service"

2. In the activity, the control of music playback, bind a number op with bundle, and then use startservice (intent). After the service is sent out
Bundle bundle = new bundle ();
Bundle. putint ("op", OP );
Intent. putextras (bundle );

Startservice (intent );

3. In the service, the startservice (intent) started by the activity is processed. The service calls the START process of the Service in sequence: oncreate --> onstart (which can be called multiple times) --> ondestroy

Oncreate (), create mediaplayer

Onstart (), obtain bundle = intent. getextras ();, extract int op = bundle. getint ("op");, and then perform the response music playing Operation

Ondestroy (), stop and release the mediaplayer Music Resource. If you call this method when context. stopservice () is executed

4. In activity, close and exit in the onclick () function have different execution meanings:

Close: Only this. Finish () is executed. If this activity form is closed, the service is not disabled, and the music is still played in the background.

Exit: The stopservice (intent) is called first. if the service is disabled, ondestroy () in 3 is called to stop and release music resources. finish (); closes this activity form

Source code download

6. expand knowledge(Process and declaration cycle)

The Android operating system tries to maintain the application process for as long as possible, but when the available memory is very low, part of the process will eventually be removed. How to determine which programs can run and which are to be destroyed? Android allows every process to run on an important level. Low-level processes are most likely to be eliminated, with a total of five levels, the following lists are arranged by importance:

1. A front-end process displays what the user needs to process and display at this time. Any of the following conditions is true. This process is considered to be running on the frontend.
A is interacting with the user.
B. It controls a basic service required for user interaction.
C has a service (such as oncreate (), OnStar (), ondestroy () that is calling the lifecycle callback function ())
D. It has a broadcast receiving object that is running the onreceive () method.
Only a few front-end processes can run at any given time. Destroying them is the system's last resort and the final choice-when the memory is insufficient for the system to continue running. In general, the device has reached the memory paging state, so some foreground processes are killed to ensure that they can respond to user needs.

2. An available process does not have any front-end components, but it can still affect the user interface. In the following two cases, the process can be called an available process.
It is a non-foreground activity, but it is still available to users (the onpause () method has been called). This may happen, for example: the front-end activity is a dialog box that allows the previous activity to be visible, that is, the current activity is translucent. You can see the interface of the previous activity. It is a service that serves the available activity.

3. A service process is a service started by calling the startservice () method, and does not belong to the first two cases. Although service processes are not directly visible to users, they are really concerned about users, such as playing music or downloading data in the background. Therefore, the system guarantees that they will not be terminated until all foreground visible programs are running normally.

4. A background process is a non-currently running activity (the onstop () method of the activity has been called) and does not directly affect the user experience, when there is not enough memory to run foreground visible programs, they will be terminated. Generally, many background processes are running, so they maintain a list of recently used LRU programs to ensure that the last running activity can be terminated. If an activity correctly implements the lifecycle method and saves its current status, killing these processes will not affect the user experience.

5. A blank thread does not run any available application groups. The only reason they are retained is to set up a cache mechanism to speed up component startup. The system often kills these memories to balance the resources of the entire system, and the resources between the process cache and the basic core cache.
Android regards the activity or service with the highest priority as the priority of the process. For example, if a process has a service and a visible activity, the process will be defined as a visible process rather than a service process.

In addition, if other processes depend on a specific process, the depended process will increase the priority. If a process serves another process, the process that provides the service will not be inferior to the process that receives the service. For example, if a content provider of process a serves a client of process B, or a service of process a is bound by a component of process B, process A has at least the same priority as process B, or higher.

Because the priority of a process that runs a service is higher than that of the process that runs the background activity, an activity prepares an operation that runs for a long time to start a service, instead of starting a thread-especially this operation may drag the activity down. For example, when playing music in the background and sending a photo to the server through the camera, starting a Service will ensure that this operation is at least running under the priority of the service process, no matter what happens to this activity, the broadcast receiver should act as an empty service rather than simply placing time-consuming operations in a single thread.

Reference recommendations:

Android service learning

Android service lifecycle and usage

Service/broadcast for Android Lifecycle

Android broadcastreceiver Learning

Use of broadcastreceiver for Android

Android broadcastreceiver starts Service

Service (Android Developer)

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.