各位看官们大家好,上一回中咱们说的是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的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!
本文详细介绍Android中服务的绑定及通信过程,包括创建服务、重写onBind方法、自定义Binder子类、实现ServiceConnection接口等关键步骤,并通过代码示例演示如何在Activity与服务间进行通信。
374

被折叠的 条评论
为什么被折叠?



