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

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

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

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

从众所周知的马的嘴…

在开发你的应用程序时,你可能会发现有必要在整个应用程序中共享数据、上下文或服务。例如,如果你的应用程序有会话数据,比如当前登录的用户,你可能会想要公开这些信息。在Android中,解决这个问题的模式是让你的Android .app.Application实例拥有所有的全局数据,然后把你的Application实例当作一个具有各种数据和服务的静态访问器的单例。

当编写一个Android应用程序时,你保证只有一个Android .app. application类的实例,所以它是安全的(谷歌Android团队推荐)将其视为单例。也就是说,您可以安全地将静态getInstance()方法添加到应用程序实现中。像这样:

public class AndroidApplication extends Application {

    private static AndroidApplication sInstance;

    public static AndroidApplication getInstance(){
        return sInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
    }
}

应用程序与单例不一样。原因如下:

应用程序的方法(如onCreate)在ui线程中调用; Singleton的方法可以在任何线程中调用; 在Application的onCreate方法中,可以实例化Handler; 如果单例是在无ui线程中执行的,则不能 实例化处理程序; 应用程序具有管理的生命周期的能力 activity。它有方法 “registerActivityLifecycleCallbacks”。但是单身人士没有 能力。