Latest web development tutorials

Android Service (Service)

Service is a component running in the background, the implementation of a long-running task and does not require user interaction. Even if the application is destroyed also still work. Services comprising essentially two states -

status description
Started Android application components, such as activities, through startService () to start the service, the service is Started state. Once started, the service can run in the background indefinitely, timely launch of its components have been destroyed.
Bound When Android application components through bindService () to bind the service, the service is Bound state. Bound state service provides a client-server interface to allow the components to interact with the service, such as sending a request to obtain the results, even for inter-process communication through IPC.

Service has a life cycle approach can be implemented to monitor service status changes can be performed at the appropriate stage. The following shows the left when the service () is created by startService when the declaration period, the right is displayed when the service () is created by bindService life cycle:

imageimage

To create the service, you need to create a class that inherits from the base class Service or its known subclass Java classes. Service base class defines the different methods and the most important callback method. You do not need to implement all of the callback method. Nevertheless, to understand all the methods is very important. These callbacks can ensure that your application to the user's desired manner.

Callback description
onStartCommand () Other components (such as activity) by calling startService () to start the service request, the system calls the method. If you implement this method, you have the responsibility to stop the service when the work is completed by stopSelf () or stopService () method.
onBind When you want to bind the other components and services through bindService (), the system calls the method. If you implement this method, you need to return IBinder object to provide an interface for customers to communicate with the service. You must implement this method, if you do not allow binding, simply return null.
onUnbind () When a customer interface for all special interrupt service release, the system calls the method.
onRebind () When a new client connection to the service, and after it has been disconnected by onUnbind (Intent) notification, the system calls the method.
onCreate () When services through onStartCommand () and onBind () is first created, the system calls the method. The call requires the implementation of a one-time installation.
onDestroy () When the service is no longer useful or destroyed, the system calls the method. Your service need to implement this method to clean up any resources, such as threads, registered listeners, receivers, and so on.

The following main service demonstrates the life cycle of each method -

package cn.uprogrammer.androidservices;

import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;

public class HelloService extends Service {

    /** 标识服务如果被杀死之后的行为 */
    int mStartMode;

    /** 绑定的客户端接口 */
    IBinder mBinder;

    /** 标识是否可以使用onRebind */
    boolean mAllowRebind;

    /** 当服务被创建时调用. */
    @Override
    public void onCreate() {

    }

    /** 调用startService()启动服务时回调 */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return mStartMode;
    }

    /** 通过bindService()绑定到服务的客户端 */
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    /** 通过unbindService()解除所有客户端绑定时调用 */
    @Override
    public boolean onUnbind(Intent intent) {
        return mAllowRebind;
    }

    /** 通过bindService()将客户端绑定到服务时调用*/
    @Override
    public void onRebind(Intent intent) {

    }

    /** 服务不再有用且将要被销毁时调用 */
    @Override
    public void onDestroy() {

    }
}

Examples

This example will show you simple steps on how to create your own Android service. Follow these steps to modify Android application previously created in the Hello World Examples section:

step description
1 Using Android Studio IDE to create an Android application and name androidservices at cn.uprogrammer.androidservices package. Similar examples Hello World section.
2 Modify the main active file MainActivity.java add startService () and stopService () method.
3 Create a new Java file MyService.java in package cn.uprogrammer.androidservices. This file will make Android a service-related methods.
4 To define the services use <service ... /> tag in the AndroidManifest.xml file. An application can have one or more services without any restriction.
5 Modify res / layout / activity_main.xml file in the default layout, online layout contains two buttons.
6 Do not res / values ​​/ strings.xml file any constants to be modified. Android Studio will note the string value.
7 Launch Android emulator to run the application and verify the results of changes made to the application.

Here is the main activity file src / cn.uprogrammer.androidservices / MainActivity.java file modified content. This file contains all the basic life-cycle approach. We've added startService () and stopService () method to start and stop the service.

package cn.uprogrammer.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));
    }
}

The following is the content of src / cn.uprogrammer.androidservices / MyService.java of. This file can implement one or more services associated with the method based on demand. For newcomers, we only realize onStartCommand () and onDestroy () -

package cn.uprogrammer.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();
    }
}

We will modify AndroidManifest.xml file. Here add <service ... /> tag to include our services:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.uprogrammer.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>

The following is the content of res / layout / activity_main.xml file contains two buttons:

<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 服务实例"
        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.uprogrammer.cn"
        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="启动服务"
        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="停止服务"
        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>

Here is the content of res / values ​​/ strings.xml is to define 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 just run a modified My Application application. I assume you've created AVD during the installation environment. Open your project in the active file, click on the toolbar image Icon to run the application In Android Studio. Android Studio install the application on the AVD and starts it. If all goes well, it will be displayed on the emulator window as follows:

image

Now click on "Start Service" button to start the service, which will execute onStartCommand we write () method, a "service has been launched" message appears at the bottom of the simulator, as follows:

image

Click on the bottom of the "out of service" button, you can stop the service.