回顾这篇文章,列举了使用单例对象的几个问题
并且已经看到了几个使用单例模式的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类的子类中。
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.