Android开发中经常会用到Context,从英文角度释义“场景”。从程序角度,Context是一个抽象类,通过代码可以发现Activity、Service、Application都是Context的子类。
Activity、Service、Application都是继承自ContextWrapper。
接下来我们来看看Context与ApplicationContext,前者是Activity的Context,后者是Application的Context。
Activity的Context肯定跟随Activity的生命周期而变化,后一种Application的Context随着Application的变化而变化,跟随Application的一生。
Application的Context是一个全局静态变量,SDK的说明是只有当你引用这个context的生命周期超过了当前activity的生命周期,而和整个应用的生命周期挂钩时,才去使用这个application的context。
一种推荐的用法就是应用程序注册广播broadcast时,使用这个context。
引用application context并不会导致内存泄漏。引用activity的context才会导致内存泄漏,当你的引用对象的生命周期超过了当前activity的生命周期时,系统回收你的activity时发现还有一个context的强引用,而不去销毁这个activity,导致内存泄漏,在开发过程中,需要非常重视这点(一个全局静态变量在引用context时一定要使用application的Context, 而不要使用activity的)
There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.