什么时候用startService,什么时候用bindService

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;
	}
}







  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值