Android 后台服务和前台服务有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3538728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between a background and foreground service?
提问by Andrew Guenther
I am currently writing my first Android application and I keep running into references to background and foreground services. Since I intend on using a service in my application I was hoping to get a clarification between the two and how they are used.
我目前正在编写我的第一个 Android 应用程序,并且不断遇到对后台和前台服务的引用。由于我打算在我的应用程序中使用一项服务,因此我希望在两者之间以及它们的使用方式之间得到澄清。
采纳答案by Asahi
Perhaps this will answer your question:
也许这会回答你的问题:
A started service can use the startForeground API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm.
一个已启动的服务可以使用 startForeground API 将服务置于前台状态,在这种状态下,系统认为它是用户主动知道的东西,因此不会在内存不足时被杀死。默认情况下服务是后台的,这意味着如果系统需要杀死它们以回收更多内存(例如在 Web 浏览器中显示大页面),它们可以被杀死而不会造成太大伤害。
More info can be found here
更多信息可以在这里找到
回答by DineshKumar
Foreground: The process relies on onPause() and onResume()...i.e you play music player and pressing pause and play
前台:该过程依赖于 onPause() 和 onResume()...即您播放音乐播放器并按下暂停并播放
Background: The process which runs without user interaction i.e receiving a message, incoming call, receiving mails, or setting alarms. The method used here is onStart() and onStop().
背景:在没有用户交互的情况下运行的过程,即接收消息、来电、接收邮件或设置警报。这里使用的方法是 onStart() 和 onStop()。
For example, check it on your phone. Create an alarm at 6:30am. When the system clock reaches 6:30am it fires. In order to kill the alarm service, just go to menu-->settings-->application-->Running service-->click stop service. It stops the alarm service even when your system reaches the time it won't fire.
例如,在您的手机上查看。在早上 6:30 创建闹钟。当系统时钟到达早上 6:30 时,它会触发。要关闭报警服务,只需进入菜单-->设置-->应用程序-->运行服务-->点击停止服务。即使您的系统达到不会触发的时间,它也会停止警报服务。
回答by Samir Elekberov
Foreground Service
is used when User is interaction with application and when Service
is doing something visible to user. Background Service
is used when even user close application (discard from recents) and when Service
is doing something not visible to user like downloading data from server, load data from a ContentProvider
etc.. And Foreground Service
is less likely to be killed by system on low memory.
Foreground Service
当用户与应用程序交互以及Service
执行用户可见的操作时使用。Background Service
甚至在用户关闭应用程序(从最近的应用程序中丢弃)以及在Service
执行用户不可见的操作时使用,例如从服务器下载数据、从 a 加载数据ContentProvider
等。并且Foreground Service
不太可能在内存不足的情况下被系统杀死。