Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 将上下文用作静态变量的错误做法?_Android_Static_Resources_Android Context - Fatal编程技术网

Android 将上下文用作静态变量的错误做法?

Android 将上下文用作静态变量的错误做法?,android,static,resources,android-context,Android,Static,Resources,Android Context,我有一个关于使用上下文作为静态变量的问题 我的代码是这样的 public class MyClass{ private static Context con = AnotherClass.getContext(); private static String fileName = con.getResources().getString(R.string.file_name); //rest of the code } 以这种方式实施它是一种不好的做法吗?我需要在创建类时读

我有一个关于使用上下文作为静态变量的问题

我的代码是这样的

public class MyClass{
   private static Context con = AnotherClass.getContext();
   private static String fileName = con.getResources().getString(R.string.file_name);

   //rest of the code
}
以这种方式实施它是一种不好的做法吗?我需要在创建类时读取文件名,因为其中有一些其他静态方法,可以随时调用


该应用程序运行良好,符合预期。我只是想知道这个实现是否有任何缺点。

不要保留对上下文活动的长期引用对活动的引用应该与活动本身具有相同的生命周期。您可以使用应用程序类并公开一个静态方法来获取ApplicationContext。@Atrix1987您好,这正是我要做的。getContext方法从扩展Application.ok的另一个类返回ApplicationContext,因此您正在对应用程序上下文进行子分类。如果您是从应用程序类获取ApplicationContext,则应该可以。或者,如果您不想对应用程序进行子类化