简体   繁体   English

如何绑定启动完成后启动的Android服务?

[英]How do I bind to Android service that is started after boot completed?

I have an Android app with a Service, and an Activity_A and an Activity_B. 我有一个带有服务的Android应用,以及一个Activity_A和一个Activity_B。

The service has to start after boot completed (which is does). 该服务必须在启动完成后启动(确实如此)。 When I launch the app, the service has to bind to Activity_A. 启动应用程序时,该服务必须绑定到Activity_A。 When Activity_B is launched, it has to unbind from Activity_A and bind to Activity_B. 启动Activity_B时,它必须与Activity_A解除绑定并绑定到Activity_B。 The Service must never be destroyed since boot completed. 自启动完成以来,绝不能销毁该服务。 That's all I need. 这就是我所需要的。

I tried two methods of binding to the server and both had problems: 我尝试了两种绑定到服务器的方法,但都遇到了问题:

  • Method 1: 方法1:

     Intent intent = new Intent(this, MyService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 

    This destroys the Service when it binds from Activity_A to Activity_B. 当它从Activity_A绑定到Activity_B时,这会破坏服务。

  • Method 2: 方法2:

     Intent intent = new Intent(this, MyService.class); startService(intent); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 

    This seems to create a new service when Activity_A is launched. 启动Activity_A时,这似乎会创建一个新服务。 (But it should bind to the Service that has been created after boot completed) (但是它应该绑定到引导完成后创建的服务)

Do you have any tips how to solve this problem? 您有如何解决此问题的提示吗?

Okay, so Method 2 works totally fine. 好的,方法2可以正常工作。 I figured that another problem occured that caused trouble. 我发现发生了另一个引起麻烦的问题。 So I successfully use Method 2 now! 因此,我现在成功地使用了方法2!

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

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