P_K*_*ing 12 service lifecycle android
我正在使用自定义Application类开发一个应用程序,它初始化了几个单例,以便它们在所有应用程序工作时间内生存.我的应用程序中还有一些与这些单例一起使用的服务.可能的情况是,应用程序类将被服务器之前的单例实例的Android销毁,因此服务将无法使用它们吗?或者应用程序总是为它的上下文服务而生活?找到解决这种情况的最佳方法是什么?
谢谢.
应用程序对象是任何Android应用程序的主要绝对起点.它将始终存在于任何Manifest声明的项目之前,例如Activity,Service和BroadcastReceiver.所以放松一下,单身人士会在你身边.
这是一个很大的讨论主题,你可以谷歌更多关于它,所以接下来是我个人的意见.无论你的单身人士(数据库,位图缓存,FileUtils)的原因是什么,我认为在应用程序的第一个入口点(即应用程序)初始化它们是正确和正确的.但是应用程序本身不是用于携带或保存这些对象的对象,这样我建议的设计方法是:
=>在你的单身对象/类上你必须:
private static MySingletonClass instance; // reference to the single object
private MySingletonClass(Context c){ // private constructor to avoid construction from anywhere else
// let's say it needs the context for construction because it's a database singleton
}
public static MySingletonClass get(){ //
if(instance == null) throw new RuntimeException("This singleton must be initialised before anything else");
return instance;
}
public static void init(Context c){ // call the initialisation from the Application
instance = new MySingletonClass(c);
}
Run Code Online (Sandbox Code Playgroud)
=>然后在您的Application对象上,您只需初始化单例
onCreate(){
MySingletonClass.init(getApplicationContext());
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您将保持必要的初始化,强制执行单例模式,但访问您调用该对象类而不是应用程序的对象.我知道这只是组织上的差异,但我相信这就是好的和坏的代码分开的原因.
因此,例如在您的服务上,呼叫是:MySingletonClass.get()并且永远不应该MyApplication.mySingle.
希望能帮助到你.
| 归档时间: |
|
| 查看次数: |
2943 次 |
| 最近记录: |