public static Application getApplication() {
if (Looper.getMainLooper() != Looper.myLooper()) {
final Object obj = new Object();
final Application[] res = {null};
synchronized (obj) {
try {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
res[0] = getApplication();
obj.notify();
}
});
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return res[0];
}
try {
return (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
try {
return (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
注意:
建议不要用反射,比较耗时,可以在application的onCreate中存一个静态变量
网友评论