1

I am inside a class inside my android app, how can I get the apps main context and activity?

Thanks for your help!

beans
  • 1,765
  • 5
  • 25
  • 31
  • 3
    This question as is, is impossible to answer. Please provide more details on your problem. What have you tried so far? What does your code look like? Also, see this: http://stackoverflow.com/questions/how-to-ask – Kurtis Nusbaum Oct 27 '11 at 15:05
  • Couldn't have given more information besides "a class"? All we could assume is that it inherits from Object. – Stealth Rabbi Oct 27 '11 at 15:21

3 Answers3

26

I am sure you already have the context but you don't know that it is the context:

Context is an abstract base class a lot of classes are inherited from.

Therefore when ever the class you are writing code for is one of the following you have you context by using the this reference:

  • ContextWrapper
  • MockContext
  • AbstractInputMethodService
  • AccessibilityService
  • AccountAuthenticatorActivity
  • Activity
  • ActivityGroup
  • AliasActivity
  • Application
  • BackupAgent
  • BackupAgentHelper
  • ContextThemeWrapper
  • ExpandableListActivity
  • InputMethodService
  • IntentService
  • IsolatedContext
  • LauncherActivity
  • ListActivity
  • MockApplication
  • MutableContextWrapper
  • NativeActivity
  • PreferenceActivity
  • RecognitionService
  • RemoteViewsService
  • RenamingDelegatingContext
  • Service
  • SpellCheckerService
  • TabActivity
  • TextToSpeechService
  • VpnService
  • WallpaperService

Hence you can write:

Context context = this;

or

Context context = (Context) this;
Robert
  • 39,162
  • 17
  • 99
  • 152
1

If it's a custom view: there is a paramater context which is your activity.

Activity activity = (Activity)context;

If it's a different class just send the activity in the constrctor.

Raz
  • 8,918
  • 3
  • 27
  • 40
0

As @Robert mentioned, Context is an abstract class and what you have are structures:

Context < ContextWrapper < Application

Context < ContextWrapper < ContextThemeWrapper < Activity

Context < ContextWrapper < ContextThemeWrapper < Activity < ListActivity

Context < ContextWrapper < Service

Context < ContextWrapper < Service < IntentService

So, all of those classes are contexts in their own way. You can cast Service and ListActivity to Context if you wish. But if you look closely, some of the classes inherit theme as well. In activity or fragment, you would like theming to be applied to your views, but don't care about it elsewhere.

I explain the difference in contexts here.

lomza
  • 9,412
  • 15
  • 70
  • 85