Android Context原理与使用的总结

来源:互联网 发布:苏州大学网络计费系统 编辑:程序博客网 时间:2024/05/31 19:08


一、Context继承体系 与 Context是如何创建的

1. Context继承体系

只用记住一句:Activity 、 Service 与Application 都是继承自ContextWrapper,而ContextWrapper implements Context。每个:Activity 、 Service 与Application都是一个Context实例。


2. Context 何时创建、怎样创建的 - 查看源码

Android应用程序窗口(Activity)的运行上下文环境(Context)的创建过程分析

Android 内核--Context对象

Android中Context详解 ---- 你所不知道的Context

以上3篇文章都是从源码角度分析Context何时创建的,但是对于平时的开发来说,仅需要知道Activity 与Service 都是继承自Context,只要创建新的Activity 或者 Service 实例,都是创建新的Context实例。

Context 总数 = Activity个数 + Service 个数 + 1个ApplicationContext

可以通过命令行 查看Context的个数
adb shell dumpsys meminfo package_name


二、关于Context的疑问

1. getBaseContext 与 getApplicationContext 区别?
持有Activity的Context 相当于持有Context,而持有AppliactionContex全局仅有这一个

2. 视图中的Context从哪来的?
例如:new TextView(Context);
通常在一个Activity中传入的就是当前Activity或者Activity.getBaseContext(),所以通过View.getContext()其实就是当前Activity的引用。

常见场景,Adapter通常通过构造器传递Context,用于getView 时inflate 视图。但是getView最有一个参数是parentView 这个是ListView对象本身,可以通过parentView.getContext获取Context对象减少手动传递。

3. Context 会出错的地方
Dialog.Builder必须传入Activity,而不能传入Activity.getApplicationContext()

4. Context作用,查看方法
访问资源、创建视图、创建四大组件

Context是什么?

参考资料: 
Android源码分析-全面理解Context
Android中Context的总结及其用法

三 内存溢出,因为引用Context导致

1. Context导致内存溢出的原因:
Avoiding memory leaks 、 Avoiding memory leaks
Android - what's the difference between the various methods to get a Context?

以上文章讲解的很详细可以查看文章,以下是简单描述:
最常见的内存形式是Bitmap未得到释放,而图片通常ImageView持有导致ImageView也不会被GC释放,创建ImageView肯定需要Context,这个Context是Activity。
Bitmap -> ImageView -> Contex(Activity)
如果Activity总是不能得到释放,导致内存不足最终OOM


2. 对于生命周期很长的对象,使用ApplicationContext,以下文档介绍自定义Application可以在项目全局都很方便获取Application Context的方法

使用自定义Application,需要Context对象时传入,避免因持有Context导致的内存溢出。因为ApplicationContext全局仅有一个实例,而多个Activity本身继承自Context,就是多个Context实例。
Android中Activity共享变量的另一方法:Application context
谈谈Android里的Context的使用!!!

4. Context内存溢出相关资料
Android学习系列(36)--App调试内存泄露之Context篇(上)
Android学习系列(37)--App调试内存泄露之Context篇(下)

四、自己创建Context

Android获取其他包的Context实例然后干坏事
http://chroya.iteye.com/blog/761441




1 0