什么时候明智地使用bindService和何时startService [英] when is smart to use bindService and when startService

查看:59
本文介绍了什么时候明智地使用bindService和何时startService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但我想知道何时使用 bindService 以及何时使用 startService .

例如:

如果我将 bindService BIND_AUTO_CREATE 一起使用,则该服务将按如下所示自动启动和创建:解决方案

如果您的调用组件( Activity )需要与以下组件通信,则通常使用 bindService()通过 ServiceConnection 启动的 Service .如果您不想与 Service 通信,则可以仅使用 startService().您可以在下面看到服务和绑定服务之间的区别.

从文档中:

开始

当应用程序组件(例如活动)通过调用startService()启动服务时,将启动"服务.启动后,即使启动该服务的组件被破坏,服务也可以无限期在后台运行.通常,已启动的服务执行一次操作,并且不返回结果给调用者.例如,它可能通过网络下载或上传文件.操作完成后,服务应自行停止.

绑定

当应用程序组件通过调用bindService()绑定到服务时,该服务被绑定".绑定服务提供了一个客户端-服务器界面,该界面允许组件与该服务进行交互,发送请求,获取结果,甚至跨进程间通信(IPC)进行交互.只要绑定了另一个应用程序组件,绑定服务就会运行.多个组件可以一次绑定到该服务,但是当所有组件取消绑定时,该服务将被破坏.

您可以在此处了解更多信息: Android服务http://developer.android.com/reference/android/content/Context.html#BIND_AUTO_CREATE

When is it smart then to use bindService and when startService? I really don't understand these two correctly.

解决方案

You usually use bindService() if your calling component(Activity) will need to communicate with the Service that you are starting, through the ServiceConnection. If you do not want to communicate with the Service you can use just startService(). You Can see below diffrence between service and bind service.

From the docs :

Started

A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.

Bound

A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

You can read more here : Android Services, Bound Services

这篇关于什么时候明智地使用bindService和何时startService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆