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

Android Service 與 Activity 資料互動

編輯:關於 Android 程式設計

Service 與 Activity 的資料互動可透過 bound service 完成。Activity 呼叫 bindService,Service 於 onBind 回傳 Binder,Activity 再透過 ServiceConnection 取得 Binder 並呼叫 Service 方法。

Service 端

public class HelloService extends Service {
    private final MyBinder binder = new MyBinder();

    public class MyBinder extends Binder {
        public HelloService getService() {
            return HelloService.this;
        }
    }

    public IBinder onBind(Intent intent) {
        return binder;
    }

    public int getRandom() {
        return new Random().nextInt(100);
    }
}

Activity 端

在 onServiceConnected 中將 IBinder 轉型為自訂 Binder,再取得 Service 實例。若需更複雜的跨行程資料傳遞,也可使用 Parcel 與 transact。

private ServiceConnection connection = new ServiceConnection() {
    public void onServiceConnected(ComponentName name, IBinder service) {
        MyBinder binder = (MyBinder) service;
        helloService = binder.getService();
    }
    public void onServiceDisconnected(ComponentName name) {
    }
};

使用完畢後呼叫 unbindService,避免資源殘留。

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