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

Android Service 全解:start、bind、IntentService 與 AIDL 跨行程

編輯:關於 Android 程式設計

為什麼要用 Service 開新執行緒,而不是在 Activity 裡開

三個理由:

  1. Activity 一旦被使用者退出,所屬行程就變成「空行程」(沒有任何活動元件),系統在需要記憶體時會優先終止它。
  2. 宿主行程被終止,行程內所有子執行緒也會跟著結束,耗時任務可能還沒跑完就中斷。
  3. 當然,兩種方式都能處理耗時任務,差別只在適用場景。

一、以 start 啟動

這種方式下,啟動者與 Service 之間沒有關聯,啟動者退出後 Service 仍會繼續執行。

生命週期:onCreate() → onStartCommand() → onDestroy()

public class NormalService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;      // start 模式下用不到
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "啟動成功", Toast.LENGTH_SHORT).show();
        Log.d("NormalService", "啟動成功");
        // 一般會在這裡開新執行緒執行耗時操作
        return super.onStartCommand(intent, flags, startId);
    }
}

清單檔註冊:

<service android:name="com.android.servicetest.service.NormalService" />

Activity 中啟動:

private void startNormal() {
    Intent nomalIntent = new Intent();
    nomalIntent.setClass(this, NormalService.class);
    startService(nomalIntent);
}

要注意的是,Service 預設運行在主執行緒,所以 onStartCommand 裡不能直接跑耗時工作,否則一樣會 ANR。「Service 就等於背景執行緒」是常見的誤解。

二、以 bind 啟動

這種方式下,綁定者與 Service 綁在一起,綁定者退出,Service 也就隨之終止。

生命週期:onCreate() → onBind() → onUnbind() → onDestroy()

public class BinderService extends Service {

    private int count;
    private MyBinder mBinder;

    @Override
    public IBinder onBind(Intent arg0) {
        if (mBinder == null) {
            mBinder = new MyBinder();
        }
        Toast.makeText(this, "綁定成功", Toast.LENGTH_SHORT).show();
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                        count++;
                    } catch (Exception e) { }
                }
            }
        }).start();
    }

    public class MyBinder extends Binder {
        public int getCount() {
            return count;
        }
    }
}

Activity 側透過 ServiceConnection 取得 Binder:

private MyBinder mBinder;

private ServiceConnection conn = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName arg0) { }

    @Override
    public void onServiceConnected(ComponentName arg0, IBinder binder) {
        mBinder = (BinderService.MyBinder) binder;
    }
};

private void bindService() {
    Intent bindIntent = new Intent();
    bindIntent.setClass(this, BinderService.class);
    bindService(bindIntent, conn, Service.BIND_AUTO_CREATE);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unbindService(conn);
}

Binder 物件相當於 Service 的內部鉤子。其他元件綁定時,Service 把 Binder 傳回去,對方就能透過它與 Service 即時溝通——這也是「查詢 Service 內部狀態」最方便的做法。

三、IntentService:處理非同步請求

IntentService 是 Service 的子類,多了幾項能力:

  • 用佇列管理請求 Intent。每次客戶端呼叫 startService,Intent 就被排進佇列,然後開一條 worker 執行緒處理,不阻塞主執行緒。
  • 依序處理佇列中的 Intent,保證同一時刻只處理一個。
  • 佇列清空後自動停止自己,不必手動 stopService。
public class IntentServiceTest extends IntentService {

    public IntentServiceTest() {
        super("IntentService");      // 執行緒名稱,便於除錯
    }

    @Override
    protected void onHandleIntent(Intent arg0) {
        Toast.makeText(this, "啟動成功", Toast.LENGTH_SHORT).show();
        Log.d("IntentServiceTest", "啟動成功");
        // 這裡可以放心執行耗時操作
        long endTime = System.currentTimeMillis() + 20 * 1000;
        while (System.currentTimeMillis() < endTime) {
            synchronized (this) {
                try {
                    wait(endTime - System.currentTimeMillis());
                } catch (Exception e) { }
            }
        }
    }
}

註冊與啟動方式和普通 Service 相同。實務上,凡是「把任務丟進背景排隊做」的需求——上傳、同步、寫入大量資料——IntentService 幾乎都是首選,因為它幫你省掉了執行緒管理與自我停止的麻煩。

四、跨行程呼叫:AIDL Service

Android 中每個 App 都跑在自己的行程裡,行程之間無法直接交換資料。要跨行程通信,Android 提供了 AIDL Service。

1. 定義 AIDL 檔(副檔名必須是 .aidl):

package com.android.servicetest.service;

interface IMusic {
    String getName();
    String getYear();
}

ADT 會自動在 gen/ 底下產生 IMusic 介面,其中包含一個 Stub 內部類。Stub 同時實作了 IMusic 與 IBinder,作為遠端 Service 的回呼類。

2. 實作 Service

public class MusicService extends Service {

    private MusicBinder mBinder;

    @Override
    public IBinder onBind(Intent arg0) {
        if (mBinder == null) {
            mBinder = new MusicBinder();
        }
        Toast.makeText(this, "綁定成功", Toast.LENGTH_SHORT).show();
        return mBinder;
    }

    public class MusicBinder extends IMusic.Stub {
        @Override
        public String getName() throws RemoteException {
            return "本草綱目";
        }

        @Override
        public String getYear() throws RemoteException {
            return "2006";
        }
    }
}

3. 客戶端綁定並呼叫

private IMusic musicService;

private ServiceConnection connAidl = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName arg0) { }

    @Override
    public void onServiceConnected(ComponentName arg0, IBinder binder) {
        // 取得 OnBind 回傳物件的「代理」
        musicService = IMusic.Stub.asInterface(binder);
    }
};

private void bindAidlService() {
    Intent aidlIntent = new Intent();
    aidlIntent.setClass(this, MusicService.class);
    bindService(aidlIntent, connAidl, Service.BIND_AUTO_CREATE);
}

private void showContent() {
    String content = "";
    try {
        content = musicService.getYear() + " " + musicService.getName();
    } catch (Exception e) { }
    Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unbindService(connAidl);
}

和綁定本地 Service 的差别很小,唯一關鍵是取得回呼的方式:本地 Service 直接拿到 OnBind 的傳回值;遠端 Service 拿到的是該物件的代理,透過 Stub.asInterface(binder) 轉回介面型別。同行程時這個代理就是原物件,跨行程時則是一個走 Binder 的 proxy——這也是為什麼 AIDL 方法都要 throws RemoteException。

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