Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Service 全攻略:本地、可通訊、前台與遠端服務一次搞懂

編輯:關於 Android 程式設計

前言

Service 是 Android 四大組件之一,應用範圍很廣。本文從最基礎的生命週期談起,並依序說明本地 Service、可通訊 Service、前台 Service 與遠端 Service 四種型態的實作方式。


目錄


一、Service 的分類

1.1 型別概覽

1.2 各型別的特點


二、實際用法解析

2.1 本地 Service

這是最普遍、最常用的一種背景服務形式。

使用步驟

步驟一:建立子類別繼承 Service,並重新實作 onCreate()、onStartCommand()、onDestroy() 與 onBind()。
步驟二:建立用來啟動 Service 的 Intent 物件。
步驟三:呼叫 startService() 啟動服務,呼叫 stopService() 停止服務。
步驟四:在 AndroidManifest.xml 註冊 Service。

範例 Demo

建議先下載 Demo 再閱讀(Carson.ho 的 GitHub):Demo_for_Service

MyService.java

public class MyService extends Service {

    // 啟動 Service 之後,就可以在 onCreate() 或 onStartCommand() 裡執行具體邏輯
    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("執行了 onCreate()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("執行了 onStartCommand()");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("執行了 onDestroy()");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

在主版面配置兩個 Button,分別用於啟動與停止 Service:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="scut.carson_ho.demo_service.MainActivity">

    <Button
        android:id="@+id/startService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="啟動服務" />

    <Button
        android:id="@+id/stopService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/startService"
        android:layout_centerInParent="true"
        android:text="停止服務" />
</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button startService;
    private Button stopService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startService = (Button) findViewById(R.id.startService);
        stopService = (Button) findViewById(R.id.stopService);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.startService:
                Intent startIntent = new Intent(this, MyService.class);
                startService(startIntent);
                break;

            case R.id.stopService:
                Intent stopIntent = new Intent(this, MyService.class);
                stopService(stopIntent);
                break;
        }
    }
}

AndroidManifest.xml

<manifest package="scut.carson_ho.demo_service"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <application>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- 註冊 Service -->
        <service android:name=".MyService" />
    </application>
</manifest>

AndroidManifest 中 Service 常見屬性說明

android:name:Service 的類別名稱。
android:label:Service 顯示名稱,不設定則預設為類別名。
android:icon:Service 的圖示。
android:permission:宣告此 Service 的權限,只有具備該權限的 App 才能控制或連線此服務。
android:process:表示該服務是否在另一個行程中執行(遠端服務)。不設定則預設為本地服務。
android:enabled:預設為 true,表示系統會啟動此 Service。
android:exported:該服務是否能被其他 App 控制或連線,不設定則預設為 false。

測試結果:

Demo 位置:Carson.ho 的 GitHub:Demo_for_Service

2.2 可通訊的 Service

前面介紹的是最基礎的形式,但只能單向使用,無法與 Activity 雙向溝通。接下來在原本基礎上加上「與 Activity 通訊」的能力,做法是綁定 Service,用到 Binder 類別、bindService()、onBind()、unbindService() 與 onUnbind()。

範例 Demo

建議先下載 Demo 再閱讀:Carson.ho 的 GitHub Demo_for_Service

MyService.java

public class MyService extends Service {

    private MyBinder mBinder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("執行了 onCreate()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("執行了 onStartCommand()");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("執行了 onDestroy()");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("執行了 onBind()");
        // 回傳實例
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("執行了 onUnbind()");
        return super.onUnbind(intent);
    }

    // 建立繼承自 Binder 的內部類別
    class MyBinder extends Binder {
        public void service_connect_Activity() {
            System.out.println("Service 關聯了 Activity,並在 Activity 執行了 Service 的方法");
        }
    }
}

版面配置再加上「綁定服務」與「解綁服務」兩個按鈕:

<Button
    android:id="@+id/bindService"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/stopService"
    android:layout_centerInParent="true"
    android:text="綁定服務" />

<Button
    android:id="@+id/unbindService"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/bindService"
    android:layout_centerInParent="true"
    android:text="解綁服務" />

在 Activity 中透過呼叫 MyBinder 的 public 方法,就能實現 Activity 指揮 Service 做事的效果。

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button startService;
    private Button stopService;
    private Button bindService;
    private Button unbindService;
    private MyService.MyBinder myBinder;

    // 建立 ServiceConnection 匿名類別
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) { }

        // Activity 與 Service 建立關聯時呼叫
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 向下轉型取得 MyBinder 實例
            myBinder = (MyService.MyBinder) service;
            // 在 Activity 中呼叫 Service 的方法
            myBinder.service_connect_Activity();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startService = (Button) findViewById(R.id.startService);
        stopService = (Button) findViewById(R.id.stopService);
        bindService = (Button) findViewById(R.id.bindService);
        unbindService = (Button) findViewById(R.id.unbindService);

        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
        bindService.setOnClickListener(this);
        unbindService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.startService:
                startService(new Intent(this, MyService.class));
                break;

            case R.id.stopService:
                stopService(new Intent(this, MyService.class));
                break;

            case R.id.bindService:
                Intent bindIntent = new Intent(this, MyService.class);
                // 參數一:Intent 物件
                // 參數二:ServiceConnection 實例
                // 參數三:標誌位,BIND_AUTO_CREATE 表示建立關聯後自動建立 Service
                // 此時 onCreate() 會執行,但 onStartCommand() 不會執行
                bindService(bindIntent, connection, BIND_AUTO_CREATE);
                break;

            case R.id.unbindService:
                unbindService(connection);
                break;

            default:
                break;
        }
    }
}

Demo:Carson.ho 的 GitHub Demo_for_Service

2.3 前台 Service

前台 Service 與後台 Service(一般形式)最大的差別在於:前台 Service 會在下拉通知欄顯示通知,後台 Service 不會。

用法很簡單,只需稍微修改原本的 onCreate() 方法即可:

@Override
public void onCreate() {
    super.onCreate();
    System.out.println("執行了 onCreate()");

    // 建立「點擊通知後開啟 MainActivity」的 Intent 物件
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    // 建立 Notification Builder 物件
    Notification.Builder builer = new Notification.Builder(this);
    builer.setContentTitle("前台服務通知的標題");
    builer.setContentText("前台服務通知的內容");
    builer.setSmallIcon(R.mipmap.ic_launcher);
    builer.setContentIntent(pendingIntent);

    Notification notification = builer.getNotification();

    // 讓 Service 變成前台 Service,並在系統狀態欄顯示出來
    startForeground(1, notification);
}

測試結果:執行後點擊「啟動服務」或「綁定服務」,Service 就會以前台模式啟動,通知欄上會出現通知。

2.4 遠端 Service

具體實作請參考另一篇文章:Android:遠端服務 Service(含 AIDL & IPC 講解)。

三、該怎麼選?使用場景對照

搞懂了各型別的用法之後,接下來的問題是:什麼時候該用哪一種?各類 Service 的適用場景可參考下圖。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved