Runoob Tutorial ArchiveEnglish

Android Service

Android Service

A service is a background-running component that performs long-running tasks that do not require user interaction. It can continue to work even if the application is destroyed. Services basically have two states -

State Description
Started If an Android application component, such as an Activity, starts a service using startService(), the service is in the Started state. Once started, the service can run indefinitely in the background, even if the component that started it has been destroyed.
Bound When an Android application component binds to a service using bindService(), the service is in the Bound state. A service in the Bound state provides a client-server interface to allow components to interact with the service, such as sending requests, retrieving results, or even performing cross-process communication via IPC.

Services have lifecycle methods that allow monitoring changes in service state and executing tasks at appropriate stages. The left diagram below shows the lifecycle when a service is created via startService(), and the right diagram shows the lifecycle when a service is created via bindService():

Image

To create a service, you need to create a Java class that inherits from the Service base class or one of its known subclasses. The Service base class defines various callback methods and most important methods. You do not need to implement all the callback methods. Nevertheless, understanding all the methods is very important. Implementing these callbacks ensures that your application behaves as the user expects.

Callback Description
onStartCommand() When other components (such as Activities) request to start a service by calling startService(), the system calls this method. If you implement this method, you are responsible for stopping the service using stopSelf() or stopService() when the work is finished.
onBind When other components want to bind to the service via bindService(), the system calls this method. If you implement this method, you must return an IBinder object to provide an interface for clients to communicate with the service. You must implement this method; if you do not allow binding, return null directly.
onUnbind() When a client unbinds from all special interfaces published by the service, the system calls this method.
onRebind() When a new client connects to the service, and it previously notified disconnection via onUnbind(Intent), the system calls this method.
onCreate() When the service is created for the first time via onStartCommand() and onBind(), the system calls this method. This call requires a one-time installation.
onDestroy() The system calls this method when the service is no longer needed or is destroyed. Your service needs to implement this method to clean up any resources, such as threads, registered listeners, receivers, etc.

The main service below demonstrates the lifecycle of each method -

Original prompt (Chinese, left untranslated)

package com.runoob.androidservices;



import android.app.Service;

import android.os.IBinder;

import android.content.Intent;

import android.os.Bundle;



public class HelloService extends Service {



    /** Behavior of the service after it is killed */

    int mStartMode;



    /** Bound client interface */

    IBinder mBinder;



    /** Indicates whether onRebind can be used */

    boolean mAllowRebind;



    /** Called when the service is created. */

    @Override

    public void onCreate() {



    }



    /** Callback when calling startService() to start the service */

    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        return mStartMode;

    }



    /** Client that binds to the service using bindService() */

    @Override

    public IBinder onBind(Intent intent) {

        return mBinder;

    }



    /** Called when all client bindings are released via unbindService() */

    @Override

    public boolean onUnbind(Intent intent) {

        return mAllowRebind;

    }



    /** Called when the client binds to the service using bindService()*/

    @Override

    public void onRebind(Intent intent) {



    }



    /** Called when the service is no longer useful and is about to be destroyed */

    @Override

    public void onDestroy() {



    }

}


Instance

This example will show you how to create your own Android service in simple steps. Modify the Android application you created in the Hello World instance chapter by following the steps below:

Steps Description
1 Use the Android Studio IDE to create an Android application and name it androidservices in the com.runoob.androidservices package. Similar to the Hello World instance chapter.
2 Modify MainActivity.java to add startService() and stopService() methods.
3 Create a new Java file MyService.java in the package com.runoob.androidservices. This file will implement Android service related methods.
4 Define the service in the AndroidManifest.xml file using the <service.../> tag. An application can have one or more services without any restrictions.
5 Modify the default layout in res/layout/activity_main.xml to include two buttons in a LinearLayout.
6 Do not modify any constants in res/values/strings.xml. Android Studio will handle the string values.
7 Start the Android emulator to run the application and verify the results of the changes made to the application.

Below are the modifications to the main activity file src/com.runoob.androidservices/MainActivity.java. This file contains all basic lifecycle methods. We added startService() and stopService() methods to start and stop the service.

package com.runoob.androidservices;



import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;





import android.content.Intent;

import android.view.View;



public class MainActivity extends Activity {



    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }



    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;

    }



    // Method to start the service

    public void startService(View view) {

        startService(new Intent(getBaseContext(), MyService.class));

    }



    // Method to stop the service

    public void stopService(View view) {

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

    }

}

Below is the content of src/com.runoob.androidservices/MyService.java. This file can implement one or more service-related methods based on requirements. For beginners, we only implement onStartCommand() and onDestroy() -

Original prompt (Chinese, left untranslated)

package com.runoob.androidservices;



import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.widget.Toast;



public class MyService extends Service {



    @Override

    public IBinder onBind(Intent arg0) {

        return null;

    }



    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        // Let it continue running until it is stopped.

        Toast.makeText(this, "服务已经启动", Toast.LENGTH_LONG).show();

        return START_STICKY;

    }



    @Override

    public void onDestroy() {

        super.onDestroy();

        Toast.makeText(this, "服务已经停止", Toast.LENGTH_LONG).show();

    }

}

Below we will modify the AndroidManifest.xml file. Here we add the <service.../> tag to include our service:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.runoob.androidservices"

    android:versionCode="1"

    android:versionName="1.0">



    <uses-sdk

        android:minSdkVersion="13"

        android:targetSdkVersion="22" />



    <application

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >



        <activity

            android:name=".MainActivity"

            android:label="@string/title_activity_main" >



            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER"/>

            </intent-filter>



        </activity>



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



    </application>



</manifest>

Below is the content of res/layout/activity_main.xml file, which contains two buttons:

Original prompt (Chinese, left untranslated)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">



    <TextView

        android:id="@+id/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Android service instance"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:textSize="30dp" />



    <TextView

        android:id="@+id/textView2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="www.runoob.com"

        android:textColor="#ff87ff09"

        android:textSize="30dp"

        android:layout_above="@+id/imageButton"

        android:layout_centerHorizontal="true"

        android:layout_marginBottom="40dp" />



    <ImageButton

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/imageButton"

        android:src="@drawable/ic_launcher"

        android:layout_centerVertical="true"

        android:layout_centerHorizontal="true" />



    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/button2"

        android:text="Start service"

        android:onClick="startService"

        android:layout_below="@+id/imageButton"

        android:layout_centerHorizontal="true" />



    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Stop service"

        android:id="@+id/button"

        android:onClick="stopService"

        android:layout_below="@+id/button2"

        android:layout_alignLeft="@+id/button2"

        android:layout_alignStart="@+id/button2"

        android:layout_alignRight="@+id/button2"

        android:layout_alignEnd="@+id/button2" />



</RelativeLayout>

Below is the content of res/values/strings.xml, defining two new constants:

<?xml version="1.0" encoding="utf-8"?>

<resources>



    <string name="app_name">Android Services</string>

    <string name="title_activity_main">MainActivity</string>

    <string name="menu_settings">Settings</string>

    <string name="action_settings">Settings</string>



</resources>

Let's run the modified My Application. I assume you have created an AVD during the installation environment setup. Open the active file in your project and click the icon in the toolbarImageto run the application in Android Studio. Android Studio installs and starts the application on the AVD. If everything goes well, it will display as follows in the emulator window:

android services 1 1

Now click the "Start Service" button to start the service, which will execute the onStartCommand() method we wrote, and a "Service started" message will appear at the bottom of the emulator, like this:

Image

Clicking the "Stop Service" button at the bottom can stop the service.