简体   繁体   English

将服务绑定放在onStart()上不好吗?

[英]is it bad to put service binding at onStart()?

I have Two activities here. 我在这里有两个活动 Each of them will interact with a single Service i tried to Bind with . 他们每个人都会与我尝试与绑定的单个服务进行交互。

But is it bad if I put in every onStart() method of each activities the binding code? 但是如果我将每个活动的每个onStart()方法都放入绑定代码是否不好

protected void onStart() {
  super.onStart();
  if(playIntent==null){
    playIntent = new Intent(this, MusicService.class);
    bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
    startService(playIntent);
  }
}

What about if from Activity - A i go to Activity - B , and then pressing the Back button? 如果从“ 活动-A”转到“ 活动B” ,然后按“上一步”按钮,该怎么办? Would it be okay because Android will call onStart() method again, which means rebinding it again? 可以,因为Android会再次调用onStart()方法 ,这意味着重新绑定它吗?

Rebinding twice from same Activity would it be bad practice or something? 从同一活动重新绑定两次,这是不好的做法还是什么?

The reference i got about the activity process is taken from here. 我从中获得有关活动过程的参考

This is what i found on android developer site: 这是我在android开发人员网站上找到的:

  1. You should usually pair the binding and unbinding during matching bring-up and 您通常应在匹配提示和
    tear-down moments of the client's lifecycle. 客户生命周期的拆除时刻。

    For example: 例如:

  2. If you only need to interact with the service while your activity is visible, you should bind during onStart() and unbind during onStop(). 如果仅在活动可见时需要与服务交互,则应在onStart()期间绑定,而在onStop()期间取消绑定。

  3. If you want your activity to receive responses even while it is stopped in the background, then you can bind during onCreate() and unbind during onDestroy(). 如果您希望活动即使在后台停止也能收到响应,则可以在onCreate()期间绑定,而在onDestroy()期间取消绑定。

    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. 注意:通常,在活动的onResume()和onPause()期间,您不应绑定和解除绑定,因为这些回调在每个生命周期转换时都会发生,并且应将在这些转换时发生的处理减到最少。 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). 此外,如果应用程序中的多个活动绑定到同一服务,并且其中两个活动之间存在过渡,则该服务可能会被破坏并重新创建,因为当前活动在下一个绑定之前(暂停期间)取消绑定(在暂停期间)(在恢复期间)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM