Android Service (i)--service

Source: Internet
Author: User

First, Service brief introduction

Service is one of the four components of the Android system (activity, Service, Broadcastreceiver, ContentProvider), which is almost identical to the level of activity. But you can't do it on your own, only in the background, and you can interact with other components. Service can be used in very many applications, such as multimedia playback when the user started other activity at this time the program to continue to play in the background, such as detecting the changes in the file on the SD card, or in the background to record your geographic information changes, etc., in short, the service is always hidden in the background.

Service launches are available in two ways:Context.startservice () and Context.bindservice ()


Second, service START process

Context.startservice () Start process:

Context.startservice (), OnCreate (), OnStart (), Service running, Context.stopservice (), ondes Troy (), Service stop


Assuming that the service has not been executed, Android calls OnCreate () first and then calls OnStart ();

Assuming that the service has been executed, only OnStart () is called, so a service's OnStart method may be called repeatedly multiple times .

Assuming that StopService is directly ondestroy, assuming that the caller exits without calling StopService, the service will be executed in the background, The service's callers can shut down the service via StopService after they are started up again.

So the life cycle of calling StartService is:onCreate-OnStart(can be called multiple times)--OnDestroy


Context.bindservice () Start process:

Context.bindservice (), OnCreate (), Onbind (), Service running, Onunbind (), OnDestroy ()- > Service Stop

Onbind () will return to the client a Ibind interface instance, Ibind consent to the client callback service method, for example, get service instance, execution state or other operation. This time the caller (context, such as activity) will be bound together with the service, the context exits, Srevice will call Onunbind->ondestroy corresponding exit.

So the lifetime of the call Bindservice is: onCreate---Onbind (just once, not multiple times)--onunbind--and ondestory.

During the service each turn-off process, only onstart can be called multiple times (through multiple StartService calls), and the other oncreate,onbind,onunbind,ondestory can only be called once in a life cycle.


Third, service life cycle

Service life cycle is not as complex as activity, it only inherits OnCreate (), OnStart (), OnDestroy () three methods

When we first started the service, the OnCreate (), OnStart () methods were called, and the OnDestroy () method was executed when the service was stopped.

It is important to note that, assuming that the service is started, when we start the service again, we do not execute the OnCreate () method, but instead execute the OnStart () method directly.

It can stop itself by using the Service.stopself () method or the Service.stopselfresult () method, just to invoke the StopService () method to stop the service, no matter how many times the service method is invoked.


Iv. Service Demo sample

Below I did a simple music playback app, using StartService and Bindservice to start the local service.

Activity

public class Playmusicservice extends Activity implements Onclicklistener {Private button playbtn;private button stopbtn; Private button pausebtn;private button exitbtn;private button closebtn;private Intent Intent; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.music_service); playbtn = (Button) Findviewbyid (r.id.play), stopbtn = (button) Findviewbyid (r.id.stop);p ausebtn = (Button) Findviewbyid ( R.id.pause); exitbtn = (Button) Findviewbyid (r.id.exit); closebtn = (Button) Findviewbyid (r.id.close); Playbtn.setonclicklistener (This), Stopbtn.setonclicklistener (this),;p Ausebtn.setonclicklistener (this); Exitbtn.setonclicklistener (this); Closebtn.setonclicklistener (this);} @Overridepublic void OnClick (View v) {int op = -1;intent = new Intent ("Com.homer.service.musicService"); switch (V.getid () {case r.id.play://Play MUSICOP = 1;break;case r.id.stop://Stop Musicop = 2;break;case r.id.pause://Pause Musicop = 3; Break;case r.id.close:// Close Activitythis.finish (); break;case r.id.exit://Stopserviceop = 4;stopservice (intent); This.finish (); break;} Bundle bundle = new Bundle (), Bundle.putint ("Op", op), Intent.putextras (bundle), StartService (intent);//startservice}@ overridepublic void OnDestroy () {Super.ondestroy (); if (intent! = null) {StopService (intent);}}}


Service

public class Musicservice extends Service {private static final String TAG = "MyService";p rivate MediaPlayer mediaplayer;@ Overridepublic ibinder onbind (Intent arg0) {return null;} @Overridepublic void OnCreate () {LOG.V (TAG, "onCreate"); Toast.maketext (This, "Show Media Player", Toast.length_short). Show (); if (MediaPlayer = = null) {MediaPlayer = MediaPlayer . Create (this, r.raw.tmp); mediaplayer.setlooping (false);}} @Overridepublic void OnDestroy () {LOG.V (TAG, "OnDestroy"); Toast.maketext (This, "Stop Media Player", toast.length_short); if (mediaPlayer! = null) {mediaplayer.stop (); Mediaplayer.release ();}} @Overridepublic void OnStart (Intent Intent, int startid) {log.v (TAG, "OnStart"); if (Intent! = null) {Bundle BUNDLE = Inten  T.getextras (); if (bundle! = null) {int op = bundle.getint ("op"); switch (OP) {case 1:play (); break;case 2:stop (); break;case 3:pause (); break;}}} public void Play () {if (!mediaplayer.isplaying ()) {Mediaplayer.start ();}} public void Pause () {if (MediaPlayer! = null && MEDIAPLayer.isplaying ()) {Mediaplayer.pause ();}} public void Stop () {if (MediaPlayer! = null) {mediaplayer.stop (); try {mediaplayer.prepare ();// After calling stop, assume that you need to play again through start, before calling the Prepare function} catch (IOException ex) {ex.printstacktrace ();}}}}

Androidmanifest.xml

Brochure activity

        <activity            android:name= ". Service. Playmusicservice "            android:label=" @string/app_name "/>

Brochure Service

        <service            android:name= ". Service. Musicservice "            android:enabled=" true ">            <intent-filter>                <action android:name=" Com.homer.service.musicService "/>            </intent-filter>        </service>


Five, Code analysis

1, activity, in the Playmusicservice by rewriting the Onclicklistener Interface onclick () method to achieve the control of music playback, the music of various operations with the number of intent passed to the service

Then by constructing a intent, intent = new Intent ("com.homer.service.musicService");

Among them,Com.homer.service.musicService is the androidmanifest.xml definition of service, the above "register service"

2, activity, music playback control, the use of bundles binding digital op, through StartService (intent); Service sent out after
Bundle bundle = new bundle ();
Bundle.putint ("Op", op);
Intent.putextras (bundle);

StartService (Intent);

3, service, will handle the activity start StartService (intent); services, call the START process of the server: OnCreate---OnStart (can be called multiple times)--OnDestroy

onCreate (), Create MediaPlayer

OnStart (), by acquiring bundle bundle = Intent.getextras (), extracting int op = Bundle.getint ("Op"), and then performing a response to the music playback operation

OnDestroy (), stop and release the MediaPlayer music resource, assuming that this method is called when Context.stopservice () is executed

4, activity, the OnClick () function in the close and exit is the execution meaning is different:

Close: Only the This.finish () is executed; When the Activity window is closed, the service is not turned off and the music continues to play in the background

Exit : StopService (Intent) was called first; Service is turned off, OnDestroy () in service calls 3 to stop and release music resources before executing this.finish (); Close the Activity window


Source code Download



Vi. Expanding knowledge (process and declaration cycle)

The Android operating system tries to keep the app as long as possible, but when the available memory is very low, it's time to remove some of the process. How to determine which programs can be executed, those to be destroyed, Android to allow each process to execute on an important level, the most important low-level processes are most likely to be eliminated, and a common 5 level, the following list is ranked by importance:

11 xForeground ProcessIt shows what the user needs to process and display at this time. If any of the following conditions are true, the process is felt to be performed at the front desk.
A is interacting with the user.
b It controls a necessary primary service that interacts with the user.
C has a service (such as OnCreate (), OnStar (), OnDestroy ()) that is invoking the life cycle callback function
D It has a broadcast receive object that is executing the onreceive () method.
Only a handful of foreground processes can be executed at any given time, and destroying them is a last resort for the system-when memory is not enough for the system to continue to execute. Usually, at this point, the device has reached the memory paging state, so kill some foreground processes to ensure that the user needs to be able to respond.

21 xAvailable ProcessesThere is no foreground component, but it can still affect the user's interface. When the following two scenarios occur, you can call the process an available process.
It is a non-foreground activity, but is still available to the user (the OnPause () method has been called) this is possible, for example: the activity in the foreground is a dialog box that agrees with the previous activity, that is, the current activity is translucent, You can see the previous activity interface, which is a service that serves the active activity.

31 xService Processis a service that is started by calling the StartService () method and is not in the first two cases. Although the service process is not directly visible to the user, they are indeed the user's concern, such as background music or network download data. So the system guarantees their execution until it is not guaranteed that all of the foreground visible programs will be executed properly before terminating them.

41 xBackground Processis a non-currently executing activity (the activity's OnStop () method has been called), they do not have a direct impact on the user experience, and when there is not enough memory to execute the foreground visible program, they will be terminated. Typically, background processes will have very many executions, so they maintain an LRU list of recent applications to ensure that the activity that is often performed can be terminated last. Suppose an activity correctly implements the life cycle method, and saves its current state, killing these processes will not affect the user experience.

51 XEmpty ThreadThe only reason to keep them, no matter what application groups are available, is to set up a caching mechanism to speed up the component startup time. Systems often kill these memory to balance resources between the system's entire system's resources, process caches, and basic core caches.
Android takes the highest priority activity or service in the process as a priority for this process. For example, if a process has a service and a visible activity, the process will be defined as a visible process, not a service process.

Also, assuming that other processes depend on a process, the dependent process increases precedence. A process serves another process, so the process of delivering the service is not less than the process of getting the service. For example, if a content provider for process a serves a client in process B, or if a service of process A is bound by a component of process B, then process A has at least the same priority as process B, or higher.

Because a process that executes a service has a higher priority than a process that performs background activity, an activity prepares a long-run operation to start a service instead of starting a thread – especially if the operation is likely to drag down the activity. For example, when playing music in the background, a photo is sent to the server via the camera, and starting a service ensures that the operation is performed at least at the priority of the service process, regardless of what happened to the activity. The broadcast receiver should be a null service rather than simply putting time-consuming operations on a single thread.




Recommended References:

Android Service Learning

Android service life cycle and how to use it

Android Life cycle Service/broadcast

Android Broadcastreceiver Learning

The use of Android Broadcastreceiver

Android broadcastreceiver Boot Service


Service (Android Developer)


Android Service (i)--service

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.