Android Service (top)

Source: Internet
Author: User

A service brief

Service is a subclass of context

Service is one of the four components used to process some more time-consuming operations in the background or to perform certain tasks that require long-term operation

Second note

The service cannot perform time-consuming operations directly because all the methods in the service are executed in the main thread

If you want to perform time-consuming operations, turn on child threads

Three service features

1. No interface

2. Long running time in the background

3. Unable to start on its own

4. Single-Case mode

Four Create a new service

1. Inherit Service

 Public classMyServiceextendsService {@Override Public voidonCreate () {Super. OnCreate (); LOG.I ("HUANG", "OnCreate"); } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {LOG.I ("HUANG", "Onstartcommand"); return Super. Onstartcommand (Intent, flags, Startid); } @Nullable @Override Publicibinder onbind (Intent Intent) {log.i ("HUANG", "Onbind"); return NULL; } @Override Public BooleanOnunbind (Intent Intent) {log.i ("HUANG", "Onunbind"); return Super. Onunbind (Intent); } @Override Public voidOnDestroy () {Super. OnDestroy (); LOG.I ("HUANG", "OnDestroy"); }}

2. The Androidmanifest.xml application node inside the Configuration Service Name property must be configured with the remaining optional

<service android:name= ". Service. MyService "/>

3. Start Service StartService () or Bindservice ()

 Public classMainactivityextendsAppcompatactivityImplementsView.onclicklistener {serviceconnection mconnection;//the Connection object for the service@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Findviewbyid (R.id.start). Setonclicklistener ( This); Findviewbyid (r.id.stop). Setonclicklistener ( This); Findviewbyid (R.id.bind). Setonclicklistener ( This); Findviewbyid (R.id.unbind). Setonclicklistener ( This); } @Override Public voidOnClick (view view) {Switch(View.getid ()) { CaseR.id.start:startservice (NewIntent ( This, MyService.class));  Break;  CaseR.id.stop:stopservice (NewIntent ( This, MyService.class));  Break;  Caser.id.bind:intent Service=NewIntent ( This, MyService.class); Mconnection=Newserviceconnection () {@Override Public voidonserviceconnected (componentname name, IBinder service) {} @Override Public voidonservicedisconnected (componentname name) {}};                Bindservice (service, mconnection, context.bind_auto_create);  Break;  CaseR.id.unbind:unbindservice (mconnection);  Break; }    }}

Five service life cycle

The service life cycle differs depending on how it is started and stops service differently

When using the StartService () method to initiate the life cycle method associated with it

OnCreate (), Onstartcommand (), OnDestroy ()

OnCreate () This method is called only once when the service is created, regardless of how many times the StartService () method is called and the Bindservice () method service is only created once

Onstartcommand () Only calls the method when it is started with the StartService () method The method calls the StartService () method multiple times when the service starts running, although the service is not created multiple times But the Onstartcommand () method is called multiple times

OnDestroy () This method is called when the service is destroyed

Just call the StopService () method once to stop the service regardless of how many times it was called before the service method starts

When using the Bindservice () method to initiate the life cycle method associated with it

OnCreate (), Onbind (), Onunbind (), OnDestroy ()

OnCreate () This method is called only once when the service is created, regardless of how many times the StartService () method is called and the Bindservice () method service is only created once

Onbind () The method is called only when it is started with the Bindservice () method, which is invoked when the caller and service bindings are called when the caller and the service have already bound multiple calls to the Bindservice () method and do not cause the method to be called more than once

Onunbind () callback the method only when it is started with the Bindservice () method, which is called when the caller and service are unbound

OnDestroy () This method is called when the service is destroyed

You can stop the service multiple calls with an error whenever you call the Unbindservice () method once

If an activity has been bindservice () then activity exits must be unbindservice () otherwise error

Multiple clients can bind the same service if the service has not been started the Bindservice () method can start the service

If you start with the StartService () method and then start with the Bindservice () method (where StartService () and Bindservice () have no precedence)

StopService () or unbindservice () service will not be destroyed by this time alone

Only the StopService () and then the Unbindservice () service will be destroyed (here StopService () and Unbindservice () have no sequencing)

In other words , a service must be destroyed if both of the boot modes are stopped.

Six StartService () and bindservice () differences

1. Lead to different service life cycles

2. Different ways to stop service

3. StartService () service initiated by the system can be found in the services that are running Bindservice () the service that is started is not found in the system running services

4. StartService () The caller and the service are not related even if the caller exits the service still running Bindservice () the caller and the service are bound together as soon as the caller exits the service and terminates "die"

Seven StartService () and Bindservice () application Scenarios

Start shutdown service through StartService () and StopService () for situations where there is no interaction between the caller and the service

Starting the Shutdown service through Bindservice () and Unbindservice () is applicable to both the caller and the service requiring a method call or passing parameters

Eight Thread Process Service

Thread: is a minimum unit of CPU execution

Process: is a minimal unit inside the system an application can be understood as a process the user initiates an application operating system that allocates a memory space to the CPU to start the main thread inside the process

Service: The service is not a thread service or the process service is running inside the process (Developer.android.com/reference/android/app/service#whatisaservice)

Priority level of the nine process

The Android system tries to keep an application process as long as possible and the system kills the process only when the memory is low

The kill process is based on the priority level of the process to kill the lower level first

Priority ranking of processes foreground process > Visual process > Service process > Background process > Empty process

1. Foreground process (a process that the user is currently working on is considered to be a foreground process if any of the following conditions are met)

1.1 Running an activity that is interacting with the user (the Onresume () method has been called)

1.2 hosted a service the service binds to an activity that interacts with the user

1.3 There is a service object that is executing the life cycle method

1.4 There is a Broadcastreceiver object that is executing the life cycle method

2. Visual process (no foreground components but still can affect what the user sees on the screen a process that is considered a visual process if any of the following conditions are met)

2.1 Live an activity that is not the foreground but it is still visible to the user (the OnPause () method has been called)

2.2 Hosted a service the service is bound to a visual activity

3. Service process (there is a service running in the background app that starts with the StartService () method)

4. Background process (activity in the background task stack)

5. Empty process (no activity in background task stack)

foreground process and visual process difficult to be killed service process to protect the background process and empty process was killed the impact of little

Elevate the service process to the foreground process

 Public classMyServiceextendsService {@Override Public voidonCreate () {Super. OnCreate (); /*** Intent unspecified activity no jump * * Intent assigned activity * app in background jump to specified activity when specified activity is retired The page will go back to the top page of the application stack, regardless of when you click the notification. * App does not jump to specified activity in the background when the specified activity exits the page before the click Notification * Note: Specify activity Also restricted by the startup mode **/Intent Intent=NewIntent ( This, Mainactivity.class); Pendingintent pendingintent= Pendingintent.getactivity ( This,                99,//Requestcodeintent, pendingintent.flag_update_current); //update the same ID and pendingintent of the same requestcodeNotificationcompat.builder Builder=NewNotificationcompat.builder ( This); Builder.setsmallicon (R.mipmap.ic_launcher)//Small icons displayed in the status bar. Setlargeicon (Bitmapfactory.decoderesource (Getresources (), R.mipmap.ic_launcher))//Drop -down display of large icons. Setticker ("drip")//first appear in notification bar with rise animation effect. Setcontenttitle ("Contenttitle")//title. Setcontenttext ("ContentText")//content. Setwhen (System.currenttimemillis ())//the time the notification is generated is displayed in the notification message.. Setcontentinfo ("ContentInfo")//Display Information. SetPriority (Notificationcompat.flag_foreground_service)//Set Notification priority. SetDefaults (Notification.default_all)//Set notification default sound vibration breathing light. Setautocancel (false)//Click and Clean to remove notifications. setongoing (true)//set as an in-progress notification is typically used to represent a background task (such as playing a music file download). Setcontentintent (pendingintent); //elevate the service process to the foreground processStartforeground (100, Builder.build ()); } @Nullable @Override Publicibinder onbind (Intent Intent) {return NULL; }}

If you want to ensure that an application is not killed in the background, you can start a service with the StartService () method in the application and then elevate the service process to the foreground process.

Android Service (Next)

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.

Tags Index: