gpt4 book ai didi

java - Android 中的服务类

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:48 24 4
gpt4 key购买 nike

Service 类的用途是什么?

许多低功耗蓝牙示例使用服务类进行所有蓝牙通信、连接、断开连接、扫描设备等。 Activity 类总是从该服务类调用方法。

直接在 Activity 类中实现所有蓝牙通信怎么样?为什么没有人像那样实现而是使用服务类?

最佳答案

来自documentation :

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

基本上它是一个松散耦合的组件,独立于 Activity 生命周期。问题是在 Android 中,您无法真正控制何时创建/销毁 Activity ,因此例如,如果您在 Activity 中加载某些内容并接到电话,则您的 Activity 可能会被销毁并且更新的结果将是丢失,或者更糟糕的是,您的加载任务无法完成并保留该 Activity ,无法对其进行垃圾回收,从而造成内存泄漏。

因此,您可以为长时间运行的后台任务使用服务,但只要您需要,您就可以让它们运行,以避免再次出现内存泄漏,并善待您的资源。

Caution: It's important that your application stops its services when it's done working, to avoid wasting system resources and consuming battery power. If necessary, other components can stop the service by calling stopService(). Even if you enable binding for the service, you must always stop the service yourself if it ever received a call to onStartCommand().

关于java - Android 中的服务类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17330219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com