0

I'm looking for ways to access application context in some classes that are used in background threads.

Besides that I'm avoiding to pass the context from my UI as a parameter to every single class.

With this in mind I'm doing something like this:

public class LojaApplication extends Application {

    private static Context applicationContext;

    @Override
    public void onCreate() {
        super.onCreate();

        applicationContext = this;
    }

    public static Context getMyContext() {
        return applicationContext;
    }
}

And then using it:

public class WorkerClass {
    private final Context applicationContext;

    public WorkerClass() {
        this.context = MyApplication.getMyContext();
    }

    public void doSomeStuffOnBackground(){
        ...
        String string = applicationContext.getString(...)
        ...
    }
}

I was worried that MyApplication.getMyContext() would return null if called inside a static block, but in my tests this works as well.

Is there a scenario that this might fail? Or problems that I'm failing to predict?

The point here is that I'm trying to avoid passing the context around as a parameter. I'm aware that is possible to access the Application Context via Context.getApplicationContext() that come from the Activity, but to do that I need to pass it as a parameter, what I'm trying to avoid.

PS.: I'm aware of the limitations of Application Context vs Activity Context.

Cedulio Cezar
  • 288
  • 3
  • 10

0 Answers0