Android:静态获取上下文是一种好习惯吗?

标签 android

<分区>

目前,在我的应用程序中有以下类:

public class MyApp extends Application {

    private static Context context;

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

    public static Context getContext() {
        return MyApp.context;
    }
}

我用它在既不是 Activities 也不是 Fragment 的类中使用 Context。使用存储在此类上的上下文与使用和 Activity 作为上下文有什么区别吗?上这门课是一种很好的做法,还是我应该为任何需要它的类(class)提供一个 Activity 作为上下文?

谢谢。

最佳答案

It's there any difference between use the context stored on this class and use and activity as context?

是的。请阅读Dave Smith's epic blog post就此主题而言。总而言之:只有当您知道为什么 Application 是正确答案时才使用Application……而且很少是这样。

It is a good practice to have this class

恕我直言,通常不会。有时您可能需要一个 Application 对象,但您不需要自己的自定义子类,也不需要将其设为单例。

should I provide an activity as context to any class who needs it?

您向任何需要它的方法提供正确的 Context 实例。正如 Dave Smith 在那篇博文中所描述的,并非所有的 Context 实例都是一样的。仅当 ApplicationContext 的正确类型时才使用 Application

关于Android:静态获取上下文是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21335783/

相关文章:

java - Android - 如果未安装,如何获取应用程序图标?

android - 使用 `Screen`(ES6)时如何在 `TabNavigator`中设置Params?

java - 在 MyXMLHandlerTemp 中使用 SharedPreferences

android - 用于保存显示数据的 WebView.savePicture() 的替代方法

android - 在用户同意的情况下在 Android 中禁用蓝牙

Android Room - 简单的选择查询 - 无法访问主线程上的数据库

android - SplitApkBundle 无效。该 bundle 针对未知语言 : [gr]. google play console

android - 我可以在 Android Studio 中运行没有 HAXM 的模拟器吗?

android - Espresso 测试无法访问类文件

android - 列表和 map 标记点击