java - Android 中的服务类

标签 java android eclipse bluetooth-lowenergy

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/

相关文章:

java - Intellij IDEA 找不到包类型

Android:如何检查设备上的闪光灯是否可用?

android - Android发送短信的 Intent 是什么?

java - 组织 Java 代码的最佳方式......多个项目或按包分开?

android - 如何将gradle项目转换为android项目

java - 当没有选择 jTable 行时如何显示消息?

java - 无法访问浏览器 :Session Not Created Exception

java.lang.UnsatisfiedLinkError : Native Library: {. ..}.dll 已经加载到另一个类加载器中

android导出签名与未签名的应用程序

java - Ant 构建文件框架将 eclipse 项目变成 war ?