Created
May 16, 2019 11:27
-
-
Save twlkyao/b4a5325409db6c3304f0c04435ccc0ca to your computer and use it in GitHub Desktop.
Android get application context by reflect.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Refer from https://github.com/eleme/UETool/blob/master/uetool-base/src/main/java/me/ele/uetool/base/Application.java