Android Context---学习笔记
来源:互联网 发布:手机淘宝加音乐播放器 编辑:程序博客网 时间:2024/05/07 19:19
学习来源
Android Context 上下文 你必须知道的一切
Android中Context详解 —- 你所不知道的Context
Context相关类的继承关系
Context类
ContextIml.java类
ContextWrapper类
ContextThemeWrapper类
部分源代码在这里
Activity Service Application 本质上都是Context的子类
应用程序App共有的Context数目公式为:总Context实例个数 = Service个数 + Activity个数 + 1(Application对应的Context实例)
- 在Activity中,一般直接是传入
this
- 当在匿名内部类中,
this
不可用,需要写为XXXActivity.this
,[也可直接getApplicationContext]
具体创建Context的时机
- 创建Application对象的时机
- 创建Activity对象的时机
- 创建Service对象的时机
XXXActivity和getApplicatioinContext
返回的不是同一个对象,一个是当前Activity的实例
,一个是项目的Application的实例
package com.mooc.shader.roundimageview; import android.content.Context; public class CustomManager { private static CustomManager sInstance; private Context mContext; private CustomManager(Context context) { this.mContext = context; } public static synchronized CustomManager getInstance(Context context) { if (sInstance == null) { sInstance = new CustomManager(context); } return sInstance; } //some methods private void someOtherMethodNeedContext() { } }
这么写是没有问题的,问题在于,这个Context哪来的我们不能确定,很大的可能性,你在某个Activity里面为了方便,直接传了个this;这样问题就来了,我们的这个类中的sInstance是一个static且强引用的,在其内部引用了一个Activity作为Context,也就是说,我们的这个Activity只要我们的项目活着,就没有办法进行内存回收。而我们的Activity的生命周期肯定没这么长,所以造成了内存泄漏。
将上述代码改为
public static synchronized CustomManager getInstance(Context context) { if (sInstance == null) { sInstance = new CustomManager(context.getApplicationContext()); } return sInstance; }
解决了内存泄漏的问题
- 因为引用的是一个ApplicationContext,它的生命周期和我们的单例对象一致
Context的应用场景
NO1:启动Activity在这些类中是可以的,但是需要创建一个新的task。一般情况不推荐。
NO2:在这些类中去layout inflate是合法的,但是会使用系统默认的主题样式,如果你自定义了某些样式可能不会被使用。
NO3:在receiver为null时允许,在4.2或以上的版本中,用于获取黏性广播的当前值。(可以无视)
注:ContentProvider、BroadcastReceiver之所以在上述表格中,是因为在其内部方法中都有一个context用于使用
和UI相关的方法基本都不建议或者不可使用Application,并且,前三个操作基本不可能在Application中出现。
- 凡是跟UI相关的,都应该使用Activity做为Context来处理
- 其他的一些操作,Service,Activity,Application等实例都可以,
- 当然了,注意Context引用的持有,防止内存泄漏。
- Android Context---学习笔记
- Android学习笔记之Context
- 学习笔记--《Android内核剖析》Context
- Android学习笔记--全局获取Context
- Android学习笔记--Context到底是什么?
- Android学习笔记(四)Activiy学习——Intent,context
- android学习笔记23--------------Android基础概念Context的作用
- android学习笔记——全局获取Context的技巧
- Android源码学习笔记:Context、ActivityThread和Activity的生命周期
- Android学习笔记2-1--组件0--Context
- Android Context学习
- Android学习 Context
- Android学习之Context
- android学习3:Context
- Android 学习 context
- Android Context学习
- Android学习之Context
- Android学习 ------- Context理解
- 二叉排序树
- 小谈Servlet
- AndroidStudio2.1.3+gradle-experimental0.7.3 ndk编译带汇编(.S)的坑
- Java的数组
- 数据分析平台搭建案例
- Android Context---学习笔记
- Android使用EventBus遇到的坑!
- java 接口 实现和继承关系
- Windows上Dbgview打印log信息
- 分组背包-hdu3033
- Install Single Node Hadoop(2.7.2) on Mac
- 【EmbeddedDev】BBB上打开PWM串口并进行操作
- POJ 1182食物链_DisjointSet并查集
- 谈谈MVC模式