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

Android Service 全解析(一):startService 啟動式服務與生命週期

編輯:關於 Android 程式設計

Service 是 Android 四大組件之一,用來執行不依賴使用者介面的背景工作。它是整個 Service 系列的第一篇,本文先從最基礎的 startService() 談起,並把生命週期回呼的觸發時機看清楚。

啟動與停止

用 startService() 啟動,用 stopService() 停止,兩者透過同一個 Intent 的 action 指向目標服務。這是啟動式服務最直觀的用法。

package cn.testservice1;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;

public class MainActivity extends Activity {
    private Button mStartButton;
    private Button mStopButton;
    private Intent intent;

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

    private void init() {
        intent = new Intent();
        intent.setAction("cc.test.com");

        // 開啟服務
        mStartButton = (Button) findViewById(R.id.startButton);
        mStartButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startService(intent);
            }
        });

        // 終止服務
        mStopButton = (Button) findViewById(R.id.stopButton);
        mStopButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                stopService(intent);
            }
        });
    }
}

服務端的回呼順序

把每個回呼都印一行日誌,就能清楚看到系統的呼叫時序:onCreate() 在服務物件第一次被建立時呼叫一次,之後再不觸發;onStart() 每次啟動都會呼叫(在新版 API 中已被 onStartCommand() 取代);onStartCommand() 是目前的正式入口;onDestroy() 則在服務被停止時清理資源。

package cn.testservice1;

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

public class ServiceSubclass extends Service {

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

    public void onCreate() {
        System.out.println("---> Service onCreate()");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        System.out.println("---> Service onStart()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("---> Service onStartCommand()");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("---> Service onDestroy()");
    }
}

注意 onBind() 回傳 null,這是啟動式服務的標準寫法,代表不提供綁定能力。

佈局

<LinearLayout 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:orientation="vertical"
    android:gravity="center_horizontal">

    <Button
        android:id="@+id/startButton"
        android:layout_width="200dip"
        android:layout_height="150dip"
        android:text="啟動Service" />

    <Button
        android:id="@+id/stopButton"
        android:layout_width="200dip"
        android:layout_height="150dip"
        android:text="停止Service" />
</LinearLayout>

onStartCommand 的回傳值怎麼選

這個回傳值決定了系統在服務被強制終止後的行為,有三種常見取值:

START_STICKY:服務被殺掉後系統會嘗試重建,但重建時 Intent 為 null,因此程式碼中必須做空值判斷。

START_NOT_STICKY:服務被殺掉後不重建,除非有新的啟動請求。適合可被隨意取消的任務。

START_REDELIVER_INTENT:重建服務並重新派發最後一個未處理完的 Intent,適合不能遺漏的下單、傳輸類任務。

兩個務必記住的限制

Service 不是線程。它與應用同進程、跑在主線程上,因此不能在 onStartCommand() 裡直接做網路請求或長時間運算,否則就是 ANR。正確做法是在其中開一條子線程,或改用 IntentService。

Android 8.0 之後有後台執行限制。應用進入背景後,啟動式服務會在短時間內被系統停止。此情境應改用 startForegroundService() 並在 5 秒內發出前景服務通知,或改用 WorkManager、JobScheduler 等符合新版規範的排程 API。

接著可以往系列後續文章看:bindService() 的雙向通信、IntentService 的線程處理,以及 AIDL 的跨進程方案。

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