创建作为单例工作的服务是一种不好的做法吗?
这是多余的,并且按照您建议的方式,从Android
Service
作为应用程序组件,它执行其功能
-
Application
生命周期,反过来又受
- 系统事件。
应用程序组件的这种意图是通过以下方式实现的
- 其声明中
AndroidManifest.xml
,
- 触发它(启动/绑定/注册)和
- (由系统)创建组件的实例
Application
并将其“附加”到ApplicationThread
/ActivityThread
.
也就是说,应用程序组件与Application
由操作系统进程托管的实例和不能独立运行.
关于你的方法, 有两种情况:
1. CustomService
的默认值构造函数是私有的按照模式。
通过致电getInstance()
的单个实例CustomService
被建造。该实例只是一个Java
与以下对象没有任何共同点的对象(单例)Android
Service
应用程序组件。这onStart()
, onStartCommand()
等等方法永远不会被系统调用。
尝试启动“服务”(在清单中声明)startService(Intent) http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)将会失败IllegalAccessException: access to constructor not allowed
.
2. CustomService
的默认值构造函数是公共的(根据发布的代码)。
如果该服务声明于AndroidManifest
并且默认构造函数为空,startService()
不过不会失败getInstance()
将创建另一个实例CustomService
这不会被视为Android
Service
应用程序组件。
这不是单例。
你建议我做什么?是否有更好的方法来重用该服务,以便从其他引擎和活动中获取一些数据(例如 mProfiles 数组)?
Use Service
as per 文档 http://developer.android.com/guide/components/services.html并选择您需要的通信类型:
- 单向通信(
Activity
-->
Service
) - 用一个started Service http://developer.android.com/guide/components/services.html#CreatingStartedService并处理每个Intent
(附有您的数据,例如mProfiles
以防万一Profile
类工具Parcelable http://developer.android.com/reference/android/os/Parcelable.html) in onStartCommand()
;
- 双向通信(
Activity
<->
Service
) - 用一个bound Service http://developer.android.com/guide/components/bound-services.html并通过IBinder
.
最后,Service
in Android
是一个单例。系统中每个服务只有一个实例。它按需启动并处理所有待处理的Intent
s/绑定客户端。一旦完成或明确停止,它将被销毁。