【发布时间】:2016-01-26 21:26:58
【问题描述】:
创建一个作为单例工作的Service 是一种不好的做法吗?我的意思是 Service 永远不会停止,它包含一些其他引擎和 Activities 会使用的私有数据,所以 Service 可能有类似的东西:
public class CustomService extends Service {
private List<Profile> mProfiles;
private static CustomService instance;
public static CustomService getInstance() {
if(instance == null) {
instance = new CustomService();
}
return instance;
}
public List<Profile> getProfiles() {
return mProfiles;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
}
...
}
使用Service 而不仅仅是一个单例的原因是它必须独立于应用程序工作,因为它在启动时连接一个永远不应该关闭且不依赖于应用程序的 websocket。你会建议我做什么?有没有更好的方法来重用Service 以便从其他引擎和Activities 获得一些数据(例如mProfiles 数组)?
我在某处读到 Service 作为单例工作,但我不知道如何从应用程序中的任何其他点访问私有变量。
【问题讨论】:
-
据我所知,您不应该自己创建服务实例,而应该使用
startService()使用上下文。我不确定使用new CustomService();的后果是什么 -
您好,谢谢您的回答。但是startService会启动服务并调用onStartCommand,但这不是我想要的。我想在应用程序的 onCreate 方法上启动服务一次,然后从应用程序的任何其他点获取服务的私有变量
标签: android design-patterns singleton android-service android-lifecycle