Android 服务:绑定还是启动? [英] Android Service : bind or start?

查看:14
本文介绍了Android 服务:绑定还是启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在什么情况下我应该启动Service,在什么情况下绑定Service?例如 - 音乐服务的安卓客户端?系统的优先级是否有任何差异;是否有任何共同规则;还有什么?

In what cases should I start Service and in what case bind Service? For example - an android client for Music Service? Are the any differences in the priority for the System;are the any common rules; anything else?

推荐答案

使用 startService() 服务在您启动后将独立运行.音乐播放器就是一个很好的例子.这些运行直到他们调用 stopSelf() 或有人调用 stopService().

Use startService() for services which will run independently after you start them. Music players are a good example. These run until they call stopSelf() or someone calls stopService().

您可以通过来回发送 Intent 与正在运行的服务进行通信,但在大多数情况下,您只需启动服务并让它自行运行即可.

You can communicate with a running service by sending Intents back and forth, but for the most part, you just start the service and let it run on its own.

当服务和客户端将通过持久连接来回通信时使用 bind().一个很好的例子是导航服务,它将位置更新传输回客户端.绑定器比 Intent 更难编写,但它们确实是用于此用例的方法.

Use bind() when the service and client will be communicating back and forth over a persistent connection. A good example is a navigation service which will be transmitting location updates back to the client. Binders are a lot harder to write than intents, but they're really the way to go for this usage case.

关于优先级:当一个进程的所有活动都失去可见性时,如果该进程托管一个以 onStart() 启动的服务,则该进程将成为一个服务进​​程,否则它会成为一个后台进程.服务进程的优先级高于后台进程.android 开发者网站上的更多详细信息.

Regarding the priority: When all activities of a process lose their visibility, the process becomes a service process if it hosts a service which was started with onStart(), otherwise it becomes a background process. Service processes have a higher priority than background processes. Further details at the android developer site.

如果一个没有可见活动的服务进程需要更高的优先级(例如一个真正不应该被中断的音乐播放器),该服务可以调用startForeground().

If a service process without visible activity needs a higher priority (e.g. a music player which really should not be interrupted), the service can call startForeground().

这篇关于Android 服务:绑定还是启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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