Android静态Application.getInstance() [英] Android static Application.getInstance()

查看:296
本文介绍了Android静态Application.getInstance()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,您能帮我吗?我们正在使用扩展Android中Application的类的静态实例.

Could you help me with this situation. We are using a static instance of a class that extends Application in android.

public class MyClass extends Application {

    public static MyClass getInstance() {
        if(mInstance == null)
        {
            mInstance = new MyClass();
        }
        return mInstance;
    }

    public MyObject getMyObject() {
        return myObject;   
    }
}

MyObject应该在任何地方都可以访问,我们正在像一样访问. MyClass.getInstance().getMyObject().它在大多数时间都有效.有时,在Service方法中,此实例返回null.但是,当我们尝试打印此对象时,当我们在UserLeaveHint()或onPause()的Activity中的同一控件中立即访问该对象时,同一实例将返回有效对象,而不是null.有人可以帮我们吗?

MyObject should be accessible everywhere and we are accessing like . MyClass.getInstance().getMyObject(). It works most of the time. Sometimes in Service method this instance returns null. But when we access this object immediately in the same control within an Activity on UserLeaveHint() or onPause() when we try to print this object the same instance returns with a valid object and not null. Could someone please help us out?

推荐答案

您应该在应用程序启动时调用的OnCreate方法中以其他方式实例化单例类(而不是简单地创建新对象):

You should instantiate the singleton class with an other way (and not simply create a new object), in OnCreate method which is called when application starts:

public class MyClass extends Application {

    // Singleton instance
    private static MyClass sInstance = null;

    @Override
    public void onCreate() {
        super.onCreate();
        // Setup singleton instance
        sInstance = this;
    }

    // Getter to access Singleton instance
    public static MyClass getInstance() {
        return sInstance ; 
    }
}

并确保将此类链接到Manifest.xml中的应用程序标记

And be sure to link this class to application tag in Manifest.xml

...
<application
    android:name="package.MyClass"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
...
</application>
....

这篇关于Android静态Application.getInstance()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆