Skip to content

Instantly share code, notes, and snippets.

@twlkyao
Created May 16, 2019 11:27
Show Gist options
  • Save twlkyao/b4a5325409db6c3304f0c04435ccc0ca to your computer and use it in GitHub Desktop.
Save twlkyao/b4a5325409db6c3304f0c04435ccc0ca to your computer and use it in GitHub Desktop.
Android get application context by reflect.
import android.content.Context;
import java.lang.reflect.Method;
public class ReflectApplication {
private static Context CONTEXT;
private ReflectApplication() {
}
public static Context getApplicationContext() {
if (CONTEXT != null) {
return CONTEXT;
} else {
try {
Class activityThreadClass = Class.forName("android.app.ActivityThread");
Method method = activityThreadClass.getMethod("currentApplication");
CONTEXT = (Context) method.invoke(null);
return CONTEXT;
} catch (Exception e) {
return null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment