在Android中获取“上下文"的静态方法? [英] Static way to get 'Context' in Android?

查看:82
本文介绍了在Android中获取“上下文"的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在静态方法中获取当前的Context实例?

Is there a way to get the current Context instance inside a static method?

我正在寻找这种方式,因为我讨厌每次更改上下文"实例时都会保存.

I'm looking for that way because I hate saving the 'Context' instance each time it changes.

推荐答案

执行以下操作:

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

In the Android Manifest file, declare the following.

<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()以静态获取您的应用程序上下文.

Now everywhere call MyApplication.getAppContext() to get your application context statically.

这篇关于在Android中获取“上下文"的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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