在Android应用中,以下方法是否存在问题:

public class MyApp extends android.app.Application {

    private static MyApp instance;

    public MyApp() {
        instance = this;
    }

    public static Context getContext() {
        return instance;
    }

}

并在需要上下文的地方传递它(例如SQLiteOpenHelper)(当然不泄漏)?


当前回答

我知道最初的问题是13年前发布的,这是Kotlin版本的无处不在的上下文。

class MyApplication : Application() {
    companion object {
        @JvmStatic
        private var instance: MyApplication? = null

        @JvmStatic
        public final fun getContext(): Context? {
            return instance
        }
    }

    override fun onCreate() {
        instance = this
        super.onCreate()
    }
}

其他回答

我使用同样的方法,我建议把单例写得更好一点:

public static MyApp getInstance() {

    if (instance == null) {
        synchronized (MyApp.class) {
            if (instance == null) {
                instance = new MyApp ();
            }
        }
    }

    return instance;
}

但我不是到处使用,我使用getContext()和getApplicationContext(),我可以这样做!

我喜欢它,但我建议改用单例:

package com.mobidrone;

import android.app.Application;
import android.content.Context;

public class ApplicationContext extends Application
{
    private static ApplicationContext instance = null;

    private ApplicationContext()
    {
        instance = this;
    }

    public static Context getInstance()
    {
        if (null == instance)
        {
            instance = new ApplicationContext();
        }

        return instance;
    }
}

应用程序类:

import android.app.Application;
import android.content.Context;

public class MyApplication extends Application {

    private static Context mContext;

    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getAppContext() {
        return mContext;
    }

}

在AndroidManifest中声明应用:

<application android:name=".MyApplication"
    ...
/>

用法:

MyApplication.getAppContext()

这是一个很好的方法。我自己也用。我只建议重写onCreate来设置单例,而不是使用构造函数。

既然你提到SQLiteOpenHelper:在onCreate(),你可以打开数据库以及。

就我个人而言,我认为文档错误地说,通常不需要子类化应用程序。我认为恰恰相反:你应该总是子类化Application。

我知道最初的问题是13年前发布的,这是Kotlin版本的无处不在的上下文。

class MyApplication : Application() {
    companion object {
        @JvmStatic
        private var instance: MyApplication? = null

        @JvmStatic
        public final fun getContext(): Context? {
            return instance
        }
    }

    override fun onCreate() {
        instance = this
        super.onCreate()
    }
}