1

I am trying to generate a notification from a class, Utilities.java, outside of the subclass of Context. I've thought about providing a SingletonContext class and have looked at posts ike this. I'd like to be able to return != null Context object since the notification can be generated at any given time because it is generated from a messageReceived() callback.

What are there downsides to doing something like this:

public static Context c;    

public class MainActivity extends Activity{
    @Override
    public void onStart()
      super.onStart()
      c = this.getApplicationContext();
}

//other method somewhere outside this class
public Context getContext(){
   return MainActivity.c
}

I don't think it would be any different than putting this on the onCreate(), however, it guarantees that the context is up to date when the activity starts.

Community
  • 1
  • 1
Clocker
  • 1,316
  • 2
  • 19
  • 29

2 Answers2

5

The Context keeps a reference to this activity in memory, which you might not want. Perhaps use

this.getApplicationContext();

instead. This will still let you do file IO and most other things a context requires. Without a specific reference to this activity.

MungoRae
  • 1,912
  • 1
  • 16
  • 25
  • do you mean making c = this.getApplicationContext() within the onStart()? You're right, doing this.getApplicationContext() will actually return the Context instead of the Activity. Thanks! – Clocker Oct 29 '13 at 16:00
0

Maybe you should overwrite the onResume Method. If you open a new activity, and switch back, the onStart method will not getting invoked.

Android Lifecycle: doc

BTW: I read about problems with ApplicationContext using a dialog or toast, so if you use the context to create on of these you should use your Activity as context.

Eruvanos
  • 670
  • 7
  • 13