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

本文探讨了Android中Service的三种启动方式:startService、通过广播交互及bindService,并对比了它们之间的优劣。重点介绍了bindService的优势,包括管理Service生命周期和服务调用者的绑定关系,以及如何实现进程间通信。

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







评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值