我想要一个可以在后台运行的服务,直到我停止,即使启动它的组件被销毁并且还允许绑定到活动 . 怎么可能?
根据android绑定服务文档 - 有三种创建绑定服务的方法
-
扩展Binder类 .
-
使用Messenger .
-
使用AIDL .
我使用messenger创建了绑定服务(第二种方法) . Activity在其onStart()方法中绑定到服务,并在其onStop()方法中取消绑定 . 双向消息传递(在活动和服务之间)正常工作 . 但问题是,当活动取消绑定服务时,服务就会被破坏 . 但我想要一个可以无限期运行的服务 .
有可能作为android Services Dev Guide - "Although this documentation generally discusses these two types of services separately, your service can work both ways—it can be started (to run indefinitely) and also allow binding. It's simply a matter of whether you implement a couple callback methods: onStartCommand() to allow components to start it and onBind() to allow binding."
我还在服务中实现onStartCommand()方法并返回START_STICKY,但它永远不会被调用 . 查看dev指南中有界服务的生命周期回调,没有onStartCommand()回调方法 . 那么如何运行服务直到我们停止并允许绑定?
我在fedora 15 OS中使用eclipse平台 .
任何帮助.....
6 回答
你只需要在某处用
startService()
启动它 . 这将防止在没有更多绑定时自动停止它 .来自Service documentation,强调我的:
正如其他人所指出的,如果需要资源,它仍可能被Android杀死 . 您可以"prioritize"您的服务,如果您将其设为foreground service,则不太可能被杀死 .
我没有使用messenger服务的服务,但是我已经绑定了一个带有远程(AIDL)接口的远程服务 . 我的发现可能有所帮助 . 由于我的主要活动和服务目前已实现,因此我像使用代码一样绑定到服务
My activity implements ServiceConnection
当我在活动结束时调用 unbindService(this) ,然后就像你找到的那样,调用服务的onDestroy()方法 .
但是,如果在bindService行之前,我还显式启动了服务
那么unBind不会导致服务的onDestroy()执行 . 仍然需要在活动的onDestroy / Stop中调用unbindService,否则会泄漏服务连接 .
在我的情况下,大概该服务仍可供其他应用程序通过其远程接口绑定 .
只有在使用
startService
方法启动服务时才会调用Service.onStartCommand回调 . 由于@NickT和@JoelF已指出您需要在客户端代码中的某处(例如onCreate)中调用bindService()
调用startService()
.您可能还想查看这篇文章(有点旧,但仍然有用):“Double life of a service”并尝试提供的示例程序作者 .
为了在 service 和 activity 之间进行通信 . 您也可以使用官方Android示例中提到的Binder
http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
官方的android文档建议http://developer.android.com/guide/components/services.html#StartingAService
该项目实现了这种服务混合( BothService ),并显示 Service 如何无限运行并且还允许与 multiple activities 绑定 .
https://github.com/shanrais/BothService
如果您在Android App抽屉中添加
"Ongoing Notification"
,那么您的应用和服务将不会被杀死 .看看http://developer.android.com/guide/topics/ui/notifiers/notifications.html
您可以使用服务 Binders 并在应用程序实例级别创建单个连接实例,在应用程序的onCreate中,这将使服务保持活动状态 . 该服务必须是前台服务