各位看官們大家好,上一回中咱們說的是Android中service的例子,這一回咱們繼續說該例子。閒話休提,言歸正轉。讓我們一起Talk Android吧!
看官們,我們在上一回中介紹了綁定服務的操作步驟,不過沒有給出代碼,這一回中我們將通過代碼結合文字的方式來演示如何綁定服務,下面是詳細的步驟:
- 1.創建服務並且重寫服務中的方法,我們還是複用前面章回中的代碼,只有onBind方法的內容有變化,其它方法的內容不變;
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
Log.i(TAG, "onBind: ");
if(mBinderSub != null)
return mBinderSub;
else
throw new UnsupportedOperationException("Not yet implemented");
}
- 2.自定義Binder的子類:BinderSub,並且在類中創建func方法,該方法用來實現服務的相關操作,簡單起見,我們只是打印一行log;
class BinderSub extends Binder {
public void func() {
Log.i(TAG, "func: do something of service.");
}
}
- 3.創建BinderSub對象,並且在onBind方法中返回該對象;
private BinderSub mBinderSub = new BinderSub();
- 4.創建ConnectionImpl類並且實現ServiceConnection接口;在類中重寫onServiceConnected和onServiceDisconnected方法;
class ConnectionImpl implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "onServiceConnected: ");
//使用服務提供的func方法來實現Activity和服務通信
mBinderSub = (ServiceA.BinderSub)service;
mBinderSub.func();
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBinderSub = null;
Log.i(TAG, "onServiceDisconnected: ");
}
}
- 5.創建ConnectionImpl對象,以便在綁定和解綁定服務時使用;
private ConnectionImpl mConnection = new ConnectionImpl();
- 6.在Activity佈局中添加兩個Button,用來綁定和解綁定服務;
<Button
android:id="@+id/id_bind_service"
android:text="Bind Service"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/id_unbind_service"
android:text="UnBind Service"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
mButtonBindService = (Button)findViewById(R.id.id_bind_service);
mButtonUnBindService = (Button)findViewById(R.id.id_unbind_service);
- 7.爲步驟6中的Button添加事件監聽器,並且在監聽器中調用bindService和unbindService方法來綁定和解除綁定服務;
mButtonBindService.setOnClickListener(v ->
bindService(intent,mConnection,this.BIND_AUTO_CREATE));
mButtonUnBindService.setOnClickListener(v -> unbindService(mConnection));
下面是程序的運行結果,請大家參考:
//按下Bind Service Button,啓動並且綁定服務,同時Activity也和服務進行了通信
I/ServiceA: onCreate: ThreadID: Thread[main,5,main]
I/ServiceA: onBind:
I/ServiceA: onServiceConnected:
I/ServiceA: func: do something of service.
//按下unBind Service Button,解綁並且銷燬服務
I/ServiceA: onUnbind:
I/ServiceA: onDestroy:
各位看官,關於Android中Service的例子咱們就介紹到這裏,欲知後面還有什麼例子,且聽下回分解!