Search code examples
androidandroid-activitysingletonandroid-contextapplicationcontext

Android: ApplicationContext class


My app uses several helper classes with static methods that need a context and for that I've created an "ApplicationContext" class as follows:

import android.app.Activity;
import android.content.Context;

public class ApplicationContext {

    private Context appContext;
    private static ApplicationContext instance;

    private ApplicationContext(){}

    public void init(Context context)
    {
        appContext = context;
    }

    private Context getContext()
    {
        return appContext;
    }

    public static Context get()
    {
        return getInstance().getContext();
    }

    public static Activity getActivity()
    {
        return (Activity)getInstance().getContext();
    }

    public static Context getApplicationContext() 
    {
        return get().getApplicationContext();
    }

    public static ApplicationContext getInstance()
    {
        return instance == null ? instance = new ApplicationContext(): instance;
    }
}

and in every activity onCreate method I set the current context like this:

ApplicationContext.getInstance().init(this);

and with this, I can get an instance of the current context or activity wherever I need it as follows:

ApplicationContext.get();
ApplicationContext.getActivity();

and all is working fine, but I'm not really sure if this is considered a good practice or not.

Another option is just to declare a static context like follows:

public WeakReference<Context> context;

in -non activity- classes where I need it, set it in activities that uses that classes like this:

whateverclassname.context = this;

and access it like

if (context!=null) ... context.get()

First, I'd like to know if first approach is good practice or not, then, if it is not, I'd like to know which of the two is best or any advice on how to handle the need of a context in non-activity classes.


Solution

  • Don't do this! Context basically have two levels: One is application context that you can get inside your Activities or sub-classing Application class and mentioning it in manifest.xml. Another is Activity context, which is alive till the activity is not destroyed.

    You must use application context, where you think the operation is independent of your activity/fragment. You can freely access that using Application sub-class e.g. MyApplication.getInstance() (Here, MyApplication extends Application and getInstance() provides its instance)

    You must use Activity context, by passing activity instance directly to Context reference variables, where you think the operation must be of Activity scope. And keeping activity instance in another class's static variable will leak Activity object.