是否有一种方法来获得静态方法内的当前上下文实例?

我正在寻找这种方式,因为我讨厌保存'Context'实例每次它改变。


当前回答

这样做:

在Android Manifest文件中,声明以下内容。

<application android:name="com.xyz.MyApplication">

</application>

然后编写类:

public class MyApplication extends Application {

    private static Context context;

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

    public static Context getAppContext() {
        return MyApplication.context;
    }
}

现在在任何地方都调用MyApplication.getAppContext()来静态地获取应用程序上下文。

其他回答

科特林

open class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        mInstance = this
    }

    companion object {
        lateinit var mInstance: MyApp
        fun getContext(): Context? {
            return mInstance.applicationContext
        }
    }
}

然后得到Context

MyApp.mInstance

or

MyApp.getContext()

罗希特的回答似乎是正确的。然而,据我所知,AndroidStudio的“即时运行”依赖于在你的代码中没有静态上下文属性。

不,我想没有。不幸的是,您只能从Activity或Context的其他子类调用getApplicationContext()。而且,这个问题有点相关。

我认为你需要一个getAppContext()方法的主体:

public static Context getAppContext()
   return MyApplication.context; 

芬兰湾的科特林:

清单:

<application android:name="MyApplication">

</application>

MyApplication.kt

class MyApplication: Application() {

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

    companion object {
        lateinit var instance: MyApplication
            private set
    }
}

然后,您可以通过MyApplication.instance访问该属性