Activity 和Service绑定
当一个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;
}
}
Service和Activity的连接可以用ServiceConnection来实现。你需要实现一个新的ServiceConnection,重写onServiceConnected和onServiceDisconnected方法,一旦连接建立,你就能得到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方法,传入一个选择了要绑定的Service的Intent(显式或隐式)和一个你实现了的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交互。