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 class MyService extends Service {

    public void onCreate() {
        Log.i("HUANG", "onCreate");

    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("HUANG", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);

    @Nullable @Override
    public IBinder onBind(Intent intent) {
        Log.i("HUANG", "onBind");
        return null;

    public boolean onUnbind(Intent intent) {
        Log.i("HUANG", "onUnbind");
        return super.onUnbind(intent);

    public void 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 class MainActivity extends AppCompatActivity implements View.OnClickListener {

    ServiceConnection mConnection; //服务的连接对象

    protected void onCreate(Bundle savedInstanceState) {


    public void onClick(View view) {
        switch (view.getId()) {
                startService(new Intent(this, MyService.class));

                stopService(new Intent(this, MyService.class));

                Intent service = new Intent(this, MyService.class);
                mConnection = new ServiceConnection() {
                    public void onServiceConnected(ComponentName name, IBinder service) {}

                    public void onServiceDisconnected(ComponentName name) {}
                bindService(service, mConnection, Context.BIND_AUTO_CREATE);



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 (

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 class MyService extends Service {

    Public void onCreate() {

         * Intent does not specify Activity without jump
         * Intent has specified Activity
         * App in the background Jump to the specified Activity When the specified Activity exits, no matter which page is clicked before the notification, it will return to the top page of the application stack.
         * The application is not in the background. Jump to the specified activity. When the specified activity exits, return to the page before the click notification.
         * Note: The specified activity is also limited by the startup mode.
         * */
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                99, //requestCode
                PendingIntent.FLAG_UPDATE_CURRENT); //Update the PendingIntent of the same id and the same requestCode

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher) //The small icon displayed in the status bar
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) // Large icon for drop-down display
                .setTicker("滴滴") //First appeared in the notification bar with rising animation
                .setContentTitle("ContentTitle") //Title
                .setContentText("ContentText") //Content
                .setWhen(System.currentTimeMillis()) //The time the notification is generated will be displayed in the notification message.
                .setContentInfo("ContentInfo") //Show information
                .setPriority(NotificationCompat.FLAG_FOREGROUND_SERVICE) //Set notification priority
                .setDefaults(Notification.DEFAULT_ALL) //Set the notification to the default sound Vibration Breathing light
                .setAutoCancel(false) //Click and clean to remove the notification
                .setOngoing(true) //Set to an ongoing notification Usually used to represent a background task (such as playing music file downloads)

        / / Promote the service process to the foreground process

    @Nullable @Override
    Public IBinder 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)

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