Android Service Bind啓動調用service方法

首先定義一個Service的子類。

public class MyService extends Service {

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        //返回MyBind對象
        return new MyBinder();
    }

    private void methodInMyService() {
        Toast.makeText(getApplicationContext(), "服務裏的方法執行了。。。",
                Toast.LENGTH_SHORT).show();
    }

    /**
     * 該類用於在onBind方法執行後返回的對象,
     * 該對象對外提供了該服務裏的方法
     */
    private class MyBinder extends Binder implements IMyBinder {

        @Override
        public void invokeMethodInMyService() {
            methodInMyService();
        }
    }
}

自定義的MyBinder接口

public interface IMyBinder {

     void invokeMethodInMyService();

}

接着在Manifest.xml文件中配置該Service

<service android:name=".MyService"/>

在Activity中綁定並調用服務裏的方法

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="start"
        android:text="開啓服務"
        android:textSize="30sp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="invoke"
        android:text="調用服務的方法"
        android:textSize="30sp" />
</LinearLayout>

綁定服務的Activity:

public class MainActivity extends Activity {

    private MyConn conn;
    private Intent intent;
    private IMyBinder myBinder;

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

    //開啓服務按鈕的點擊事件
    public void start(View view) {
        intent = new Intent(this, MyService.class);
        conn = new MyConn();
        //綁定服務,
        // 第一個參數是intent對象,表面開啓的服務。
        // 第二個參數是綁定服務的監聽器
        // 第三個參數一般爲BIND_AUTO_CREATE常量,表示自動創建bind
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

    //調用服務方法按鈕的點擊事件
    public void invoke(View view) {
        myBinder.invokeMethodInMyService();
    }

    private class MyConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //iBinder爲服務裏面onBind()方法返回的對象,所以可以強轉爲IMyBinder類型
            myBinder = (IMyBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    }
}

綁定本地服務調用方法的步驟

  1. 在服務的內部創建一個內部類 提供一個方法,可以間接調用服務的方法
  2. 實現服務的onbind方法,返回的就是這個內部類
  3. 在activity 綁定服務。bindService();
  4. 在服務成功綁定的回調方法onServiceConnected, 會傳遞過來一個 IBinder對象
  5. 強制類型轉化爲自定義的接口類型,調用接口裏面的方法。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章