定義您的服務將用於通信事件的接口:
public interface ServiceCallbacks {
void doSomething();
}
寫您的服務類。您的活動將綁定到此服務,因此請按照sample shown here。另外,我們將添加一個方法來設置ServiceCallbacks
。
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();
}
這解決了我的問題。非常感謝:) – Siju
謝謝! Android Developers中有一些細節不夠明確。這幫助我了! –
謝謝。它給出了一個完美的例子 –