在Android中获取上下文?

bea*_*ans 1 android

我在我的Android应用程序内部的一个类中,如何获取应用程序的主要上下文和活动?

谢谢你的帮助!

Rob*_*ert 26

我相信你已经有了上下文,但你不知道它是上下文:

Context是一个抽象的基类,很多类都是继承自的.

因此,当您编写代码的类是以下之一时,您可以使用this引用来获取上下文:

  • ContextWrapper
  • MockContext
  • AbstractInputMethodService
  • AccessibilityService
  • AccountAuthenticatorActivity
  • 活动
  • 的ActivityGroup
  • AliasActivity
  • 应用
  • BackupAgent
  • BackupAgentHelper
  • ContextThemeWrapper
  • ExpandableListActivity
  • InputMethodService
  • IntentService
  • IsolatedContext
  • LauncherActivity
  • ListActivity
  • MockApplication
  • MutableContextWrapper
  • NativeActivity的
  • PreferenceActivity
  • RecognitionService
  • RemoteViewsService
  • RenamingDelegatingContext
  • 服务
  • SpellCheckerService
  • TabActivity
  • TextToSpeechService
  • VpnService
  • WallpaperService

因此你可以写:

Context context = this;
Run Code Online (Sandbox Code Playgroud)

要么

Context context = (Context) this;
Run Code Online (Sandbox Code Playgroud)