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

Android Service 使用全解析:啟動、綁定、生命週期與進程通信

編輯:關於 Android 程式設計

什麼是 Service

Service 是 Android 四大組件之一,主要承擔耗時的後台邏輯,或者需要長期駐留的輪詢任務。即使 Activity 退出,Service 也可以繼續在後台運行。

它有兩種啟動方式,對應不同的生命週期:

startService 啟動服務(簡單使用)
bindService 綁定服務
先啟動再綁定

Service 的簡單使用

startService 是最直觀的一種。流程三步:

創建 MyService 類繼承 Service
重寫 onCreate()、onStartCommand()、onDestroy()
在清單文件中註冊該 Service

public class MyService extends Service {
    private static final String TAG = "INFO";

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

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

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

繼承 Service 時必須實現 onBind,它只在綁定場景下用到,這裡先返回 null,後面再補。

布局裡放兩個按鈕:

<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="start"
        android:text="start_service" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="stop"
        android:text="stop_service" />
</LinearLayout>

MainActivity 中實現這兩個方法:

public void start(View view) {
    Intent intent = new Intent(this, SimpleService.class);
    startService(intent);
}

public void stop(View view) {
    Intent intent = new Intent(this, SimpleService.class);
    stopService(intent);
}

啟動方式與 Activity 類似,同樣借助 Intent,只是換成 startService 與 stopService。

最後別忘了在清單文件中註冊

<!-- 註冊服務 -->
<service android:name=".service.SimpleService" />

觀察一下日誌:

// 點擊 start 按鈕
06-20 16:09:24.483 I/INFO: onCreate
06-20 16:09:24.485 I/INFO: onStartCommand

// 再次點擊 start
06-20 16:09:27.873 I/INFO: onStartCommand

// 點擊 stop
06-20 16:09:29.442 I/INFO: onDestroy

// 退出程序(Service 已停止)→ 重新打開並點擊 start
06-20 16:09:49.545 I/INFO: onCreate
06-20 16:09:49.545 I/INFO: onStartCommand

// 未停止 Service,通過後台直接干掉程序後再進入
06-20 16:09:53.488 I/INFO: onCreate
06-20 16:09:53.489 I/INFO: onStartCommand

規律很清楚:第一次 startService() 會創建實例並依次回調 onCreate() 和 onStartCommand();此後再調用只會走 onStartCommand()。stopService 則銷毀實例。

對比兩種退出方式:先 stop 再退出,一切正常;Service 未銷毀時從後台強殺,程序退出後又出現了 onCreate 和 onStartCommand。原因是對 Service 而言這種退出屬於異常中斷,系統會重新創建實例把它拉起——這也是重新走兩個初始化方法的原因。

還有一種情況這裡沒演示,直接說結論:通過返回鍵退出程序時,若沒有手動調用 onDestroy(),Service 不會被銷毀,仍會在系統中運行。

小結:這種方式通過 startService() 啟動,反覆調用 onStartCommand() 來驅動業務,MP3 播放器之類就是典型場景。缺點是與 Activity 的數據交互比較彆扭,這時綁定方式更合適。

綁定 Service

回到之前沒管的 onBind:

@Nullable
@Override
public IBinder onBind(Intent intent) {
    // 綁定之後回調此方法
    return myBinder;
}

/** 綁定之後回傳給 Activity 的對象實例 */
public class MyBinder extends Binder {
    public void down() {
        Log.i(TAG, "down.....");
    }
}

由於 onBind() 返回 IBinder,自定義一個實現類,並在其中開一個方法,通過返回值把實例交給 Activity。

布局中再加兩個按鈕:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="bind"
    android:text="bind_service" />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="unbind"
    android:text="unbind_service" />

實現這兩個方法:

public void bind(View view) {
    Intent intent = new Intent(this, MyService.class);
    bindService(intent, conn, BIND_AUTO_CREATE);
}

public void unbind(View view) {
    unbindService(conn);
}

bindService(Intent service, ServiceConnection conn, int flags) 三個參數分別是:

service:意圖
ServiceConnection:綁定與解綁的回調類,類似 xxxListener
flag:綁定標志。BIND_AUTO_CREATE 的含義是若 Service 尚未創建則先創建再綁定

ServiceConnection 有兩個回調方法:

onServiceConnected(ComponentName name, IBinder service):綁定成功
onServiceDisconnected(ComponentName name):服務異常銷毀時(一般不會觸發)

實現如下:

private ServiceConnection conn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // 建立聯繫時回調
        myBinder = (MyService.MyBinder) service;
        myBinder.down();
        Log.i("INFO", "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // 斷開連接時回調
        Log.i("INFO", "onServiceDisconnected");
    }
};

通過 onServiceConnected 的參數即可拿到 Service 回傳的 MyBinder 實例。

06-20 16:49:06.972 I/INFO: onCreate
06-20 16:49:06.977 I/INFO: down.....
06-20 16:49:06.977 I/INFO: onServiceConnected
06-20 16:49:20.228 I/INFO: onDestroy

結論整理:

bindService 時因 flag 設置會先創建實例,再回調 onBind 返回 Binder 用於交互
unbindService 之後,若無其他綁定,Service 立即被銷毀
綁定後若不解綁,Activity 銷毀或從後台強殺都會拋異常——綁了必須解
重複 bindService() 不會有效果也不會再回調,交互完全交給 Binder 實例

flags 常用取值:

BIND_AUTO_CREATE:Service 不存在時自動創建
BIND_ADJUST_WITH_ACTIVITY:Service 重要性隨所綁定 Activity 的重要程度變化,Activity 在前台則 Service 級別更高
BIND_NOT_FOREGROUND:Service 永不獲得前台優先級
BIND_WAIVE_PRIORITY:Service 優先級不受影響
BIND_IMPORTANT:客戶端在前台時,該 Service 重要性等同前台 Activity,優先級迅速提升
BIND_ABOVE_CLIENT:Service 優先級高於 Activity,資源不足時 Activity 會先被回收

補充:Service 自身也有 unBind() 方法,當所有綁定都斷開時會回調。

先啟動再綁定服務

06-20 17:02:02.628 I/INFO: onCreate
06-20 17:02:02.628 I/INFO: onStartCommand
06-20 17:02:05.544 I/INFO: down.....
06-20 17:02:05.544 I/INFO: onServiceConnected
06-20 17:02:08.502 I/INFO: onDestroy

關鍵點只有一條:同時使用了兩種啟動方式,就必須同時調用 stop 和 unbind,Service 才會真正銷毀。

這種組合實際作用有限。

Service 的生命周期

這裡只分析 startService 和 bindService 兩種主要方式。

粘性 Service

用 startService 啟動時,若進程被後台強殺而 Service 實例未銷毀,程序結束後系統會重新拉起並再次調用 onCreate 與 onStartCommand。這個行為可以控制:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "onStartCommand");
    return super.onStartCommand(intent, flags, startId);
}

點進父類實現可以看到:

public int onStartCommand(Intent intent, int flags, int startId) {
    onStart(intent, startId);
    return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
}

所以默認就是粘性行為。改成非粘性:

public int onStartCommand(Intent intent, int flags, int startId) {
    // 非粘性標志,被異常干掉後不會重啟
    return Service.START_NOT_STICKY;
}

返回值可選值:

START_STICKY:粘性標志。進程被 kill 後保留「已啟動」狀態但不保留 intent,系統會嘗試重建 Service 並調用 onStartCommand,若期間沒有新的啟動命令,Intent 參數為 null
START_NOT_STICKY:非粘性標志。執行完 onStartCommand 後被 kill,系統不會自動重啟
START_REDELIVER_INTENT:帶數據的粘性標志。重啟時會把最後一個未處理的 Intent 重新傳入
START_STICKY_COMPATIBILITY:START_STICKY 的兼容版本,但不保證一定能重啟

Service 與 Thread、Activity 的比較

Service 與 Thread

Service 和 Thread 沒有任何關聯
Thread 開子線程執行耗時操作,不阻塞主線程
Service 本身就運行在主線程,在裡面做耗時操作一樣會 ANR

Service 與 Activity

兩者都在主線程。在 Activity 中直接開線程,線程生命週期不可控且無法共享,Activity 銷毀後就失控了;而 Service 可以與多個 Activity 綁定,各個 Activity 拿到同一個 Service 對象來操作線程,即使其中一個銷毀,其他仍能繼續使用。

前台 Service

Google 把進程分為五個級別(優先級由高到低):

前台進程:正與用戶交互的 Activity;或包含與前台綁定的 Service
可視進程:包含已 onPause 但未 onStop 的 Activity,比如 Activity 上彈出了對話框
服務進程:包含已啟動的 Service
後台進程:不含可見 Activity
空進程:不含任何活動組件

前台 Service 就是讓 Service 與一條通知綁定,類似酷狗被殺後音樂仍在播放、通知欄仍有控制項的效果。在 onCreate() 中加入:

// 點擊通知跳轉到該應用的延時意圖
Intent notificationIntent = new Intent(this, ServiceMainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

Notification notification1 = new Notification.Builder(this)
        .setContentTitle("這是通知的標題")
        .setContentText("這是通知的內容")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentIntent(pendingIntent)
        .build();

NotificationManager nService = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nService.notify(1, notification1);

// 使 Service 不被殺死
startForeground(1, notification1);

關鍵是 startForeground(),它把通知與 Service 綁定。此後即使從後台強殺應用,Service 實例依然存在且不會被銷毀,通知也仍在。點擊通知跳轉後通知不會消失,因為它與 Service 綁着;銷毀 Service 則通知立即消失。

當不再需要前台優先級時,調用 stopForeground(true) 可退回後台,並可選擇是否移除通知。

音樂播放器基本都是這個路數。

IntentService

業務場景

有一類需求很常見:一個任務拆成若干子任務,需要按順序串行執行,全部完成才算成功。用幾個線程串行也能做,但每個線程都要手動控制,前一個結束後再開下一個;或者乾脆全塞進一個線程裡順序跑。這些做法都可行,但如果是後台任務,代碼就得寫在 Service 裡,而 Service 在主線程,於是還得再開子線程。有沒有更省事的方案?有,就是 IntentService。

IntentService 是什麼

IntentService 是繼承自 Service 並處理異步請求的類。內部有一個工作線程專門處理耗時操作,啟動方式與普通 Service 相同;任務執行完畢後它會自動停止,不需要手動控制。可以多次啟動 IntentService,每個耗時操作會以工作隊列的方式在 onHandleIntent 回調中依次執行,且始終只跑一個工作線程,第一個完成後再跑第二個。

使用方式

public class MyIntentService extends IntentService {
    // 必須實現父類構造方法,參數代表線程名字
    public MyIntentService() {
        super("MyIntentService");
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("info", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // 根據不同參數執行不同任務
        String params = intent.getStringExtra("params");
        if (params.equals("1")) Log.i("info", "run service1");
        if (params.equals("2")) Log.i("info", "run service2");
        if (params.equals("3")) Log.i("info", "run service13");

        // 讓服務休眠 2 秒
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

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

三個要點:必須實現無參構造並調用 super(name),name 是工作線程名;onHandleIntent 是任務入口,運行於子線程;通過日誌觀察各方法調用順序。

// 定義三個後台任務
Intent intent1 = new Intent(this, MyIntentService.class);
intent1.putExtra("params", "1");
Intent intent2 = new Intent(this, MyIntentService.class);
intent2.putExtra("params", "2");
Intent intent3 = new Intent(this, MyIntentService.class);
intent3.putExtra("params", "3");

startService(intent1);
startService(intent2);
startService(intent3);

記得在清單文件中註冊。日誌結果:

06-21 10:19:30.546 I/info: onCreate
06-21 10:19:30.547 I/info: onStartCommand
06-21 10:19:30.548 I/info: onStartCommand
06-21 10:19:30.553 I/info: onStartCommand
06-21 10:19:30.554 I/info: run service1
06-21 10:19:32.555 I/info: run service2
06-21 10:19:34.565 I/info: run service13
06-21 10:19:36.567 I/info: onDestory

分析:onCreate 只打印一次,說明實例只創建一次;onHandleIntent 嚴格按順序執行,證明是同步的——如果是異步,加上 sleep 之後順序就不可控了;任務全部完成後自動調用 onDestroy 自我銷毀。

Service 實現簡單輪詢(推送相關)

另一類常見訴求:後台定時任務,每隔一段時間請求服務器確認狀態或拉取更新。兩種實現方式:

Timer:Java 的計時工具類。問題是 CPU 休眠(比如長時間熄屏)時無法執行,輪詢隨之中斷;靠 WakeLock 保持 CPU 喚醒可以解決,但非常耗電
AlarmManager:Android 封裝的 RTC(Real Time Clock)管理模塊。RTC 是獨立硬件時鐘,CPU 休眠時仍能正常運行,到點後通過中斷喚醒 CPU

推薦 AlarmManager,極光推送就是這個路子。

定義 LongRunningService:

public class LongRunningService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread() {
            @Override
            public void run() {
                // 網絡請求等輪詢更新操作
                Log.i("info", "更新數據");
            }
        }.start();

        // 啟動一個鬧鐘
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        // 設置提醒時間,類似鬧鐘
        int anHour = 2 * 1000;
        // 該時間是系統開機到現在的累計值,注意與 System.currentTimeMillis() 區分
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;

        Intent i = new Intent(this, LongRunningReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);

        return super.onStartCommand(intent, flags, startId);
    }
}

在 onStartCommand 中拿到 AlarmManager 並註冊鬧鐘,定時觸發廣播,由廣播再拉起 Service,閉環就成立了。

public class LongRunningReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 啟動服務
        Intent i = new Intent(context, LongRunningService.class);
        context.startService(i);
    }
}

備注:manager.set() 第二、三個參數分別是觸發時間與延時意圖;第一個參數的可選值如下。

AlarmManager.ELAPSED_REALTIME:相對時間(自開機起算),不含休眠時間,休眠狀態下無法喚醒
AlarmManager.ELAPSED_REALTIME_WAKEUP:相對時間,休眠狀態下可喚醒
AlarmManager.RTC:絕對時間(自 1970-01-01 00:00 起算),休眠狀態下不可用
AlarmManager.RTC_WAKEUP:絕對時間,休眠狀態下可喚醒並提示
AlarmManager.POWER_OFF_WAKEUP:絕對時間,關機狀態下仍能提示

AIDL 進程通信(待續)

用 Service 完成跨進程通信涉及內容較多,後續文章專門展開。

TO DO:進程間通信機制(IPC)總結。

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