Activity绑定到Service上

本文介绍了在Android中如何通过ServiceConnection实现Activity与Service之间的绑定及通信。详细解释了Service的onBind方法实现,以及如何在Activity中获取Service实例的引用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   

当一个Activity绑定到一个Service上时,它负责维护Service实例的引用,允许你对正在运行的Service进行一些方法调用。

 

Activity能进行绑定得益于Service的接口。为了支持Service的绑定,实现onBind方法如下所示:

 

private final IBinder binder = new MyBinder();

 

@Override

public IBinder onBind(Intent intent) {

return binder;

}

 

public class MyBinder extends Binder {

MyService getService()

{

return MyService.this;

}

}

 

ServiceActivity的连接可以用ServiceConnection来实现。你需要实现一个新的ServiceConnection,重写onServiceConnectedonServiceDisconnected方法,一旦连接建立,你就能得到Service实例的引用。

 

// Reference to the service

private MyService serviceBinder;

 

// Handles the connection between the service and activity

private ServiceConnection mConnection = new ServiceConnection()

{

public void onServiceConnected(ComponentName className, IBinder service) {

// Called when the connection is made.

serviceBinder = ((MyService.MyBinder)service).getService();

}

 

public void onServiceDisconnected(ComponentName className) {

// Received when the service unexpectedly disconnects.

serviceBinder = null;

}

};

 

执行绑定,调用bindService方法,传入一个选择了要绑定的ServiceIntent(显式或隐式)和一个你实现了的ServiceConnection实例,如下的框架代码所示:

 

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

// Bind to the service

Intent bindIntent = new Intent(MyActivity.this, MyService.class);

bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);

}

 

一旦Service对象找到,通过onServiceConnected处理函数中获得serviceBinder对象就能得到它的公共方法和属性。

 

Android应用程序一般不共享内存,但在有些时候,你的应用程序可能想要与其它的应用程序中运行的Service交互。

 

你可以使用广播Intent或者通过用于启动ServiceIntent中的Bundle来达到与运行在其它进程中的Service交互的目的。如果你需要更加紧密的连接的话,你可以使用AIDLService跨越程序边界来实现绑定。AIDL定义了系统级别的Service的接口,来允许Android跨越进程边界传递对象。AIDL的定义将在第11章中覆盖。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值