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

Android 編程心得:Service 資料綁定入門

編輯:關於 Android 程式設計

在 Android 裡,Service 的資料綁定是一種相當實用的手法。由於 Service 與 Activity 一樣運行在應用行程的主線程中,兩者之間有多種互動方式,本文就來說明如何透過「綁定」讓 Service 把資料回傳給 Activity。

步驟一:定義溝通用的介面

先宣告一個介面,把需要對外開放的方法定義出來:

public interface ICount {
    public int getcount();
}

步驟二:讓 Service 實作介面並提供 Binder

接著讓 Service 子類實作這個介面,並定義一個 ServiceBinder 內部類,透過它的物件來綁定資料。要特別注意的是:Service 本身就跑在主線程,若要做耗時操作,仍必須自行開啟子執行緒。至於 onBind() 的回傳型別是 IBinder,而我們的 ServiceBinder 繼承自 Binder——這是因為 Binder 正是 IBinder 的直接子類,是輕量級遠端程序呼叫機制的基礎。

public class BackGroundService extends Service implements ICount {
    private boolean disable; // 線程是否執行的標識位
    private int count;       // 計數
    private ServiceBinder serviceBinder = new ServiceBinder();

    public class ServiceBinder extends Binder implements ICount {
        @Override
        public int getcount() {
            return 0;
        }
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!disable) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) { }
                    count++;
                    System.out.println("CountService Count is " + count);
                }
            }
        }).start();
    }

    @Override
    public int getcount() {
        return count;
    }

    @Override
    public void onDestroy() {
        this.disable = true;
        System.out.println("Service destroy...");
        super.onDestroy();
    }
}

步驟三:在 AndroidManifest 註冊 Service

這裡不只聲明 Service,還要為它加上 intent 的過濾器,供後續 bind 時比對:

<service android:name="com.yqc.testservice.BackGroundService">
    <intent-filter>
        <action android:name="com.yqc.testservice.BackGroundService" />
    </intent-filter>
</service>

步驟四:在 Activity 建立綁定

前面定義的 intent 過濾器,正是拿來當作 bindService() 的參數。透過 ServiceConnection 與 Service 建立連線,並在連上時取得後台資料:

public class MainActivity extends Activity {
    Button btn_start;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.bindService(new Intent("com.yqc.testservice.BackGroundService"),
                this.serviceConnection, BIND_AUTO_CREATE);
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) { }
        });
    }

    @Override
    protected void onDestroy() {
        this.unbindService(serviceConnection);
        System.out.println("Activity Destroy...");
        super.onDestroy();
    }

    private ICount countentity;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            countentity = (ICount) service;
            System.out.println("CountService on service connected, count is " + countentity.getcount());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            countentity = null;
        }
    };
}

關鍵在於 onServiceConnected():當連線建立,我們把回傳的 IBinder 轉型成 ICount,此後就能直接呼叫 Service 暴露的方法取得資料。別忘了在 onDestroy() 中呼叫 unbindService() 解除綁定,避免資源洩漏。

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