Is there a way to get the current Context
instance inside a static method?
I\'m looking for that way because I hate saving the \'Context\' instance eac
Here is an undocumented way to get an Application (which is a Context) from anywhere in the UI thread. It relies on the hidden static method ActivityThread.currentApplication()
. It should work at least on Android 4.x.
try {
final Class> activityThreadClass =
Class.forName("android.app.ActivityThread");
final Method method = activityThreadClass.getMethod("currentApplication");
return (Application) method.invoke(null, (Object[]) null);
} catch (final ClassNotFoundException e) {
// handle exception
} catch (final NoSuchMethodException e) {
// handle exception
} catch (final IllegalArgumentException e) {
// handle exception
} catch (final IllegalAccessException e) {
// handle exception
} catch (final InvocationTargetException e) {
// handle exception
}
Note that it is possible for this method to return null, e.g. when you call the method outside of the UI thread, or the application is not bound to the thread.
It is still better to use @RohitGhatol's solution if you can change the Application code.