定义您的服务将用于传达事件的接口:
public interface ServiceCallbacks {
void doSomething();
}
编写您的服务类。 您的活动将绑定到该服务,因此请遵循此处显示的示例。 另外,我们将添加一个方法来设置setCallbacks。
public class MyService extends Service {
// Binder given to clients
private final IBinder binder = new LocalBinder();
// Registered callbacks
private ServiceCallbacks serviceCallbacks;
// Class used for the client Binder.
public class LocalBinder extends Binder {
MyService getService() {
// Return this instance of MyService so clients can call public methods
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public void setCallbacks(ServiceCallbacks callbacks) {
serviceCallbacks = callbacks;
}
}
按照相同的指南编写您的Activity类,但也要使其实现ServiceCallbacks接口。 与服务绑定/解除绑定时,将通过在服务上调用setCallbacks进行注册/注销。
public class MyActivity extends Activity implements ServiceCallbacks {
private MyService myService;
private boolean bound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
}
@Override
protected void onStart() {
super.onStart();
// bind to Service
Intent intent = new Intent(this, MyService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from service
if (bound) {
myService.setCallbacks(null); // unregister
unbindService(serviceConnection);
bound = false;
}
}
/** Callbacks for service binding, passed to bindService() */
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// cast the IBinder and get MyService instance
LocalBinder binder = (LocalBinder) service;
myService = binder.getService();
bound = true;
myService.setCallbacks(MyActivity.this); // register
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
}
};
/* Defined by ServiceCallbacks interface */
@Override
public void doSomething() {
...
}
}
现在,当您的服务想要与活动进行通信时,只需调用前面的接口方法之一即可。 服务内幕:
if (serviceCallbacks != null) {
serviceCallbacks.doSomething();
}