Android 关于绑定Services的提示

(1) 假如你只想Activity可见的时候与Service进行交互,那应该在Activity的 onStart()方法中绑定,在onStop()方法中解开绑定。

(2) 假如你想要Activity在不可见的时候(但后台仍在运行)也能与Service进行交互,那应该在Activity的 onCreate()方法中绑定,和在onDestroy()方法中解开绑定。

(3) 通常不应该在onResume()方法和onPause()方法中绑定和解开绑定,因为每次lifecycle状态转换的时候都会调用这些回调方法,假如有多个Activities绑定同一个Service,并且有两个Activities之间发生了状态转换,那么service就会被销毁和重新创建因为当前的activity会在下一个activity绑定之前停下来,与Service解开绑定。


原文:http://developer.android.com/guide/topics/fundamentals/bound-services.html

Here are some important notes about binding to a service:

  • You should always trap DeadObjectException exceptions, which are thrown when the connection has broken. This is the only exception thrown by remote methods.
  • Objects are reference counted across processes.
  • You should usually pair the binding and unbinding during matching bring-up and tear-down moments of the client's lifecycle. For example:
    • If you only need to interact with the service while your activity is visible, you should bind during onStart() and unbind during onStop().
    • If you want your activity to receive responses even while it is stopped in the background, then you can bind during onCreate() and unbind duringonDestroy(). Beware that this implies that your activity needs to use the service the entire time it's running (even in the background), so if the service is in another process, then you increase the weight of the process and it becomes more likely that the system will kill it.

    Note: You should usually not bind and unbind during your activity's onResume() and onPause(), because these callbacks occur at every lifecycle transition and you should keep the processing that occurs at these transitions to a minimum. Also, if multiple activities in your application bind to the same service and there is a transition between two of those activities, the service may be destroyed and recreated as the current activity unbinds (during pause) before the next one binds (during resume). (This activity transition for how activities coordinate their lifecycles is described in the Activities document.)


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值