Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Service 學習筆記:本地服務、生命週期與啟動模式

編輯:Android 開發實例

Service 是什麼

Service 是在一段不確定的時間內於背景執行、且不與使用者直接互動的應用元件。每個 Service 都必須在 manifest 中以 <service> 宣告,並透過 Context.startService() 或 Context.bindService() 啟動。

一個常被忽略的重點:Service 運行在應用進程的主執行緒中,和 Activity 一樣。因此任何耗時或阻塞的運算都必須另開子執行緒,否則一樣會造成 ANR。

兩種使用模式

本地服務(Local Service)

供應用內部使用。以 Context.startService() 啟動,以 Context.stopService() 結束,Service 自身也可以呼叫 stopSelf() 或 stopSelfResult() 主動停止。不論呼叫了多少次 startService(),只需一次 stopService() 就能讓它停下。

典型場景是把耗時工作從 Activity 的執行緒中剝離出去,例如背景檢查更新,讓使用者操作不被拖住。

遠端服務(Remote Service)

供系統內不同應用之間使用。它透過自訂並對外暴露的介面提供操作,客戶端以 Context.bindService() 建立連線、Context.unbindService() 關閉,且允許有多個客戶端同時綁定到同一個 Service。若 Service 尚未載入,bindService() 會先把它拉起來。

這類服務適合做成可跨應用重複利用的元件,例如天氣查詢服務,其他應用不必各自重造一遍。

生命週期

Service 的 callbacks 比 Activity 單純,主要環繞 onCreate()、onStart()(新版為 onStartCommand())與 onDestroy()。首次啟動時依序觸發 onCreate() 與 onStart(),停止時執行 onDestroy()。

關鍵細節:Service 一旦啟動,再次呼叫 startService() 不會重跑 onCreate(),而是直接進入 onStart()。

onStartCommand() 的回傳值決定服務被系統回收後的行為,有三種模式:

  • START_STICKY:適合需要持續存活、等待命令的服務。
  • START_NOT_STICKY:僅在有待處理命令時才運行。
  • START_REDELIVER_INTENT:會重新派發最後一個未完成的 Intent,適合不可中斷的工作。

startService 與 bindService 的差別

Service 不會自己啟動,兩種啟動方式的語意截然不同:

startService()

呼叫者與 Service 之間沒有關聯,即使呼叫者退出,Service 仍持續運行。若 Service 尚未建立,系統先呼叫 onCreate() 再呼叫 onStart();若已建立,重複呼叫只會多次觸發 onStart(),不會重複建立。結束只能靠 stopService(),此時觸發 onDestroy()。

bindService()

呼叫者與 Service 綁定在一起,呼叫者一旦解綁(或銷毀),Service 隨之終止。只有這種方式才會回呼 onBind(),且重複呼叫 bindService() 不會重複觸發。解除則靠 unbindService(),Service 結束時同樣走 onDestroy()。

官方文件補充了一個重要規則:Service 可以同時被 start 又被 bind。這種情況下,只要「已被 start」或「設定了 BIND_AUTO_CREATE 旗標」其中任一條件成立,系統就會讓它持續運行;兩者都不成立時才會呼叫 onDestroy()。所有清理工作(終止執行緒、取消註冊接收器)都應放在 onDestroy() 中完成。

持有 Service 的進程優先級較高

Android 會盡量保住運行 Service 的進程,因為 Service 通常代表使用者仍在意的工作。記憶體吃緊時,這類進程的優先級如下:

  1. 若 Service 正在執行 onCreate()、onStartCommand() 或 onDestroy(),其進程被視為前景進程,不會被回收。
  2. 已啟動的 Service,其進程優先級低於使用者可見的進程,但高於一般背景進程,因此通常不會被殺。
  3. 已有客戶端綁定的 Service,其進程可視為可見,優先級最高。
  4. 以 startForeground(int, Notification) 推向前景的 Service,系統視同使用者可見,記憶體不足時也不會被回收。

此外,若 Activity 等其他元件與 Service 同處一個進程,也會拉高該進程整體的重要性。

實作一:不與 Activity 互動的本地服務

這是最單純的形態,onBind() 直接回傳 null:

public class LocalService extends Service {

    private static final String TAG = "LocalService";

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

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy");
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.i(TAG, "onStart");
        super.onStart(intent, startId);
    }
}

Activity 側只需兩個按鈕:

((Button) findViewById(R.id.startLocalService)).setOnClickListener(
        new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        startService(new Intent("com.demo.SERVICE_DEMO"));
    }
});

((Button) findViewById(R.id.stopLocalService)).setOnClickListener(
        new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        stopService(new Intent("com.demo.SERVICE_DEMO"));
    }
});

manifest 中必須補上 intent-filter,否則啟動時會找不到對應的 Service:

<service android:name=".LocalService">
    <intent-filter>
        <action android:name="com.demo.SERVICE_DEMO" />
        <category android:name="android.intent.category.default" />
    </intent-filter>
</service>

實測的 callback 順序印證了前面的說明:第一次 startService 觸發 onCreate 與 onStart;在 stopService 之前,無論點擊多少次 startService,都只會再觸發 onStart;stopService 時觸發 onDestroy;而再次點擊 stopService 完全不會進入任何 callback。整個過程中 onBind() 從未被呼叫。

實作二:需要與 Activity 互動的本地服務

這種情況要讓 onBind() 回傳一個 Binder 物件,讓客戶端取得 Service 參照。官方範例(APIDemo 中的 LocalService)的做法如下:

public class LocalService extends Service {
    private NotificationManager mNM;

    /**
     * 供客戶端取用的 Binder。由於確定與客戶端同進程,
     * 不需要處理 IPC。
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }
    }

    @Override
    public void onCreate() {
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // 在狀態列顯示通知,告知服務已啟動
        showNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // 讓服務持續運行直到被明確停止
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        // 取消常駐通知
        mNM.cancel(R.string.local_service_started);
        // 告知使用者服務已停止
        Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
    }

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

    private final IBinder mBinder = new LocalBinder();

    private void showNotification() {
        CharSequence text = getText(R.string.local_service_started);

        Notification notification = new Notification(R.drawable.stat_sample, text,
                System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, LocalServiceController.class), 0);

        notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                text, contentIntent);

        mNM.notify(R.string.local_service_started, notification);
    }
}

相比第一個例子,這裡多了三件事:新增一個繼承 Binder 的公開內部類別並提供 getService();建立該 Binder 的實例;讓 onBind() 回傳它。

客戶端綁定

public class LocalServiceBinding extends Activity {

    private boolean mIsBound;
    private LocalService mBoundService;

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

        Button button = (Button) findViewById(R.id.bind);
        button.setOnClickListener(mBindListener);
        button = (Button) findViewById(R.id.unbind);
        button.setOnClickListener(mUnbindListener);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // 綁定成功,由於確定 Service 運行於自身進程,
            // 可直接把 IBinder 轉為具體類別使用
            mBoundService = ((LocalService.LocalBinder) service).getService();
            Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
                    Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {
            // 連線意外中斷(進程崩潰)。同進程時理論上不應發生
            mBoundService = null;
            Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected,
                    Toast.LENGTH_SHORT).show();
        }
    };

    private OnClickListener mBindListener = new OnClickListener() {
        public void onClick(View v) {
            bindService(new Intent(LocalServiceBinding.this, LocalService.class),
                    mConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
        }
    };

    private OnClickListener mUnbindListener = new OnClickListener() {
        public void onClick(View v) {
            if (mIsBound) {
                unbindService(mConnection);
                mIsBound = false;
            }
        }
    };
}

這裡的關鍵是 ServiceConnection:在 onServiceConnected() 中從 IBinder 取得 Service 物件,在 onServiceDisconnected() 中把它設為 null;bindService() 與 unbindService() 都是圍繞這個物件操作。

manifest 宣告:

<service android:name=".app.LocalService" />

<activity android:name=".app.LocalServiceBinding"
    android:label="@string/activity_local_service_binding">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.SAMPLE_CODE" />
    </intent-filter>
</activity>

實測 callback 順序:

  • bindService:onCreate → onBind → onServiceConnected
  • unbindService:只觸發 onDestroy

值得注意的是 onStart() 完全不會被呼叫;而 onServiceDisconnected() 之所以沒觸發,正如程式碼註解所述——同進程情況下不會出現非預期斷線。

onStartCommand() 的三個回傳常數

START_NOT_STICKY
若系統在 onStartCommand() 回傳後殺掉服務,除非還有未處理的 pending intent,否則不重建服務。這是最安全的選擇,能避免在沒有必要時讓服務空轉,適合那些工作未完成也能由應用自行重啟的情境。
START_STICKY
若服務被殺,系統會重建服務並再次呼叫 onStartCommand(),但不重新派發最後一個 intent,而是傳入 null(若有 pending intent 則會派發)。適合不按命令行事、但需要長期存活等待工作的服務,例如音樂播放器。
START_REDELIVER_INTENT
若服務被殺,系統重建後會以最後一個未完成的 intent 再次呼叫 onStartCommand(),並依序處理剩餘的 pending intent。適合必須立刻續作的工作,例如檔案下載。

讓 Service 進入前景

若希望 Service 在記憶體吃緊時仍不被回收,可使用 startForeground() 搭配 stopForeground(),並透過 Notification 讓使用者清楚知道有服務正在執行。具體用法請參考官方文件。

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