Get application context from non activity singleton class

Update: 06-Mar-18 Use MyApplication instance instead of Context instance. Application instance is a singleton context instance itself. public class MyApplication extends Application { private static MyApplication mContext; @Override public void onCreate() { super.onCreate(); mContext = this; } public static MyApplication getContext() { return mContext; } } Previous Answer You can get the the application context … Read more

What is different between MainActivity.this vs getApplicationContext()

Which context to use? There are two types of Context: Application context is associated with the application and will always be the same throughout the life of application; it does not change. So if you are using Toast, you can use application context or even activity context (both) because Toast can be displayed from anywhere … Read more

Dagger 2 injecting Android Application Context

@Module public class MainActivityModule { private final Context context; public MainActivityModule (Context context) { this.context = context; } @Provides //scope is not necessary for parameters stored within the module public Context context() { return context; } } @Component(modules={MainActivityModule.class}) @Singleton public interface MainActivityComponent { Context context(); void inject(MainActivity mainActivity); } And then MainActivityComponent mainActivityComponent = DaggerMainActivityComponent.builder() … Read more

Best practice to pass Context to non-activity classes?

You can do that using ContextWrapper, as described here. For example: public class MyContextWrapper extends ContextWrapper { public MyContextWrapper(Context base) { super(base); } public void makeMyAppAwesome(){ makeBaconAndEggsWithMeltedCheese(this); } } And call the non activity class like this from an Activity new MyContextWrapper(this);