1. 采用startService方式启动Service,然后互相发送广播,使用Intent中传递数据,这个方式显然效率不高
2. 更挫一点的方法,是用一中的方法startService之后,在onStartCommand中保存一个service对象的static全局引用,后面直接用
3. 采用bindService的方式启动Service,然后在ServiceConnection::onServiceConnected(0中保存Service对象引用,后面直接调用Service的public方法就OK了,不需要在使用Server::onBider()函数返回的Binder绕着道调用Service
其实bindService()这样用是大材小用了,我们一般用1、2两种方法就够了,必须用到bindService的情况很少。
本人的理解bindService真正的用场:
a. 管理Service的什么周期,就是讲Servcie和调用方绑定,做到共患难,同生死。(其实你用startServcie,在你需要的地方stopServcie,是一样的效果)
b. 进程间通信,这个恐怕非bindService不可了
private ServiceConnection serviceConn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
Logger.d("onServiceConnected called");
// We've bound to LocalService, cast the IBinder and get LocalService
// instance
ServiceBinder binder = (ServiceBinder) service;
scheduler = binder.getService();
}
public class WalkseeService extends Service {
private final IBinder binder = new ServiceBinder();
/**
* The Binder class that returns an instance of running service
*/
public class ServiceBinder extends Binder {
public WalkseeService getService() {
return WalkseeService.this; //这里返回Service对象
}
}
@Override
public IBinder onBind(Intent arg0) {
return this.binder;
}
}