Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android. How to Get context from different activity

I'm playing with the GCM.

Everything is perfect using the example on https://code.google.com/p/gcm/source/checkout Im getting notifications on my app with the gcm messages,

Now I want to add the message in a listView located on my MainActivity.

Im receiving my messages on a different class (GcmIntentService.java). How can I get MainActivity context to sendBroadcast.

Already tried with

private static Context mContext;

public static Context getContext() {
    return mContext;
}

public static void setContext(Context context) {
    mContext = context;
}

But is not working.

Any Ideas.

Thanks

like image 715
Carlos González Avatar asked Oct 12 '13 13:10

Carlos González


People also ask

How do I get context of a different activity?

getContext() This method can be called on a View like textView. getContext() . This will give the context of activity in which the view is currently hosted in.

How do you find the context of a non activity class?

In an android Application, is there any way to get the context in android in a non-activity class if the activity class name is known? pass the context of ur current activity to the java class constructor... If your non-activity class is a Fragment , see stackoverflow.com/questions/8215308/using-context-in-a-fragment.

How do I find application context?

You can go for getApplicationContext() if you wanna get context of whole application. If you want to get context of current class you can use getBaseContext() instead.

What is the difference between application context and activity context?

They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.


2 Answers

I am not sure what you are doing. But keeping the below in mind

Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself). http://www.curious-creature.org/2008/12/18/avoid-memory-leaks-on-android/

You can do as below

Example:

 new MyClass(ActivityName.this);

class MyClass
{
      Context mContext; 
      public MyClass(Context context)
      {
          mContext=context;
      } 
}
like image 146
Raghunandan Avatar answered Sep 27 '22 17:09

Raghunandan


pass the context variable through constructor .

like image 28
SHASHIDHAR MANCHUKONDA Avatar answered Sep 27 '22 17:09

SHASHIDHAR MANCHUKONDA