如何使用BoundService

如何使用BoundService

如何使用Service以及如何使用startService中,
解釋了甚麼是Service以及如何使用啟動式的Service,
這篇要示範使用連繫(bound)的Service。

先宣告一個Service

public class MyService extends Service {
    private MyBinder mBinder = new MyBinder();

    public class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    public String getStr(){
        return "service string";
    }
}

裡面有一個我們自己定義的Binder, 利用Binder可以跟Activity進行雙向的溝通,
Binder回傳Service的本體, 那麼就可以利用這個instance去執行Service內的任何方法。

接著來實作我們的Activity

public class MainActivity extends AppCompatActivity {
    private MyService mService;
    private ServiceConnection mLoaclServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyService.MyBinder mMyBinder = (MyService.MyBinder)service;
            mService = mMyBinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    private TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindService(new Intent(this, MyService.class), mLoaclServiceConnection, Context.BIND_AUTO_CREATE);
        text = (TextView) findViewById(R.id.text);
        Button getStr = (Button) findViewById(R.id.get_service_text);
        getStr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                text.setText(mService.getStr());
            }
        });

    }
}

在onCreate內先對service進行bind, 傳入我們自訂好的ServiceConnection物件,
Service會對這個物件呼叫Callback,
此時可以將回傳的Binder物件轉型回我們所定義的MyBinder,
透過getService就可以拿到Service的實體,
此時再call getServiceStr()方法就可以拿到Service內的字串了。

xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="Hello World!"
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text"
        android:id="@+id/get_service_text"
        android:text="get service text"/>
</RelativeLayout>





程式碼