android - 为什么 Android 需要上下文来访问资源?

标签 android

<分区>

我明白为什么 Android 要求您在尝试获取 View (例如显示 Toast 等)时传递 Context 对象。

但是,我真的不明白要求它访问可以由应用程序中的不同上下文共享的资源的意义。

我有好几次发现自己试图使用静态方法或类似的东西从实用程序类访问资源,并且发现要求传递上下文参数非常烦人。

我看不出有什么地方可以用这个来解决问题。

最佳答案

来自official documentation :

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

很明显,上下文是电话资源和您的代码之间的中间人。这似乎合乎逻辑,您无法从任何地方访问它。

您只能在 Activity 和 Application 类中访问 Context 的原因是因为它们都派生自 Context :

java.lang.Object

↳ android.content.Context

  ↳ android.content.ContextWrapper

      ↳ android.view.ContextThemeWrapper

          ↳ android.app.Activity

关于android - 为什么 Android 需要上下文来访问资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27170817/

相关文章:

java - 如何在android中使用自动完成文本

AndroidManifest.xml 没有正确的值

android - 如何使用包管理器为应用程序列表创建选择器

android - CardView 在移除高程后占用高程空间

android - 在 Android 中使用 PhotoView 显示最初的完整图像

android - 使用 Azure 通知中心时如何设置 "Quiet Time"?

java.lang.runtimeexception 无法实例化接收器

android - 使用后退按钮关闭 PopupWindow?

java - 尝试从公共(public) Google 电子表格读取数据时出现 NullPointerExceptions

java - 如何显示与 Android 的对话框?