回顾这篇文章,列举了使用单例对象的几个问题 并且已经看到了几个使用单例模式的Android应用程序的例子,我想知道使用单例而不是通过全局应用程序状态共享的单个实例是否是一个好主意(子类化Android .os. application并通过context.getApplication()获取它)。

这两种机制有什么优点/缺点?

老实说,我希望在这篇文章中得到同样的答案,单例模式与Web应用程序,不是一个好主意!但应用于Android。我说的对吗?DalvikVM有什么不同?

编辑:我想就所涉及的几个方面发表意见:

同步 可重用性 测试


当前回答

我也有同样的问题:单例还是做一个子类android.os.Application?

首先,我尝试了单例,但我的应用程序在某些时候会调用浏览器

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));

问题是,如果手机没有足够的内存,你的大多数类(甚至是单例)被清理以获得一些内存,当从浏览器返回到我的应用程序时,它每次都崩溃了。

解决方案:将需要的数据放在Application类的子类中。

其他回答

它们实际上是一样的。 我能看出一点不同。使用Application类,你可以在Application. oncreate()中初始化你的变量,并在Application. onterminate()中销毁它们。对于单例,你必须依赖VM初始化和销毁静态数据。

同时考虑这两者:

将单例对象作为类中的静态实例。 拥有一个公共类(Context),它为应用程序中的所有单例对象返回单例实例,这样做的好处是Context中的方法名将是有意义的,例如:Context . getloggedinuser()而不是User.getInstance()。

此外,我建议您扩展上下文,不仅包括对单例对象的访问,还包括需要全局访问的一些功能,例如:Context . logoffuser (), Context . readsaveddata()等。也许将Context重命名为Facade会有意义。

我的观点是:

我确实注意到,当我的活动被销毁时,一些单例/静态字段被重置。我在一些低端2.3设备上注意到了这一点。

我的案例非常简单:我只有一个私有文件“init_done”和一个静态方法“init”,我从activity.onCreate()调用。我注意到init方法在重新创建活动时重新执行了自己。

虽然我不能证明我的肯定,这可能与单例/类是什么时候第一次创建/使用有关。当活动被销毁/回收时,似乎只有这个活动引用的所有类也都被回收了。

我把我的singleton实例移动到Application的一个子类。我从应用程序实例访问它们。而且,从那以后,再也没有注意到这个问题。

我希望这能帮助到一些人。

My activity calls finish() (which doesn't make it finish immediately, but will do eventually) and calls Google Street Viewer. When I debug it on Eclipse, my connection to the app breaks when Street Viewer is called, which I understand as the (whole) application being closed, supposedly to free up memory (as a single activity being finished shouldn't cause this behavior). Nevertheless, I'm able to save state in a Bundle via onSaveInstanceState() and restore it in the onCreate() method of the next activity in the stack. Either by using a static singleton or subclassing Application I face the application closing and losing state (unless I save it in a Bundle). So from my experience they are the same with regards to state preservation. I noticed that the connection is lost in Android 4.1.2 and 4.2.2 but not on 4.0.7 or 3.2.4, which in my understanding suggests that the memory recovery mechanism has changed at some point.

来自:开发人员>参考-应用程序

通常不需要子类化Application。在大多数情况下, 静态单例可以以更模块化的方式提供相同的功能 道路如果你的单例需要一个全局上下文(例如注册 广播接收器),检索它的函数可以给出一个 在内部使用Context. getapplicationcontext()时 首先构造单例。