为您的所有活动制作一个 BaseActivity。在 BaseActivity 中,执行以下操作:
public class MyActivity extends Activity implements ServiceConnection {
//you may add @override, it's optional
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyService.class);
bindService(intent, this, 0);
}
//you may add @override, it's optional
protected void onStop() {
super.onStop();
unbindService(this);
}
public void onServiceConnected(ComponentName name, IBinder binder) {};
public void onServiceDisconnected(ComponentName name) {};
/* lots of other stuff ... */
}
您的 BaseActivity 将需要实现 ServiceConnection 接口(或者您可以使用匿名内部类),但您可以将这些方法留空。
在您的 Service 类中,您需要实现该onBind(Intent)
方法并返回一个 IBinder。最简单的方法是这样的:
public class MyService extends Service {
private final IBinder localBinder = new LocalBinder();
public void onCreate() {
super.onCreate();
// first time the service is bound, it will be created
// you can start up your timed-operations here
}
public IBinder onBind(Intent intent) {
return localBinder;
}
public void onUnbind(Intent intent) {
// called when the last Activity is unbound from this service
// stop your timed operations here
}
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
}