获取Application的Context
Posted ihrthk
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取Application的Context相关的知识,希望对你有一定的参考价值。
引言
获取Application的Context,这一直是一个比较常见的问题,现在做很多事情都需是context。一般来讲有两种办法。一是封装方法传参,二是封装静态的Application实例。
在我看来这两种办法,都不是很好。第一种的问题是在方法嵌套调用的时候有繁琐,常常出现的问题是,第一个方法需要context参数,直到第n级方法的时候才用到这个context。第二个问题是Application的实例只有一个,不需要使用static,官方也反对我们这么多。其次这么写对代码有一定的浸入性。
查看Activity的源码,自己的办法
/**
* Created by zhangls on 2016/7/6.
*/
public class ContextProvider
private static Context sContext = null;
/**
* Get application context.
*
* @return
*/
public static Context getApplicationContext()
if (sContext != null)
return sContext;
try
//1.先获取到当前的ActivityThread对象
Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
//2.获取ActivityTread的静态方法currentApplication
Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentApplication");
//隐藏Api,设置可访问
currentActivityThreadMethod.setAccessible(true);
//3.调用ActivityTread.currentApplication()
Application currentApplication = (Application) currentActivityThreadMethod.invoke(null);
sContext = currentApplication.getApplicationContext();
catch (ClassNotFoundException e)
e.printStackTrace();
catch (NoSuchMethodException e)
e.printStackTrace();
catch (IllegalAccessException e)
e.printStackTrace();
catch (InvocationTargetException e)
e.printStackTrace();
if (sContext == null)
throw new NullPointerException("Global application uninitialized");
return sContext;
private ContextProvider()
发现一个更好的实现,来自冯森林(https://github.com/oasisfeng/)。
public class App
public static final Application INSTANCE;
static
Application app = null;
try
app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
if (app == null)
throw new IllegalStateException("Static initialization of Applications must be on main thread.");
catch (final Exception e)
Log.e("Failed to get current application from AppGlobals." + e.getMessage());
try
app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
catch (final Exception ex)
Log.e("Failed to get current application from ActivityThread." + e.getMessage());
finally
INSTANCE = app;
以上是关于获取Application的Context的主要内容,如果未能解决你的问题,请参考以下文章
从tomcat context.xml而不是application.properties获取数据源
Android开发之Android Context,上下文(Activity Context, Application Context)