原文地址:打脸现场!Android面试官:Context都说不明白也来面高工?你是来搞笑的吧? https://www.jianshu.com/p/2a0cf846ade3 .
本文是对原文的改写
一 前言
Activity mActivity =new Activity();
QA:android的new对象和java的new对象一样吗?
an:不一样. java是new一个对象.android是new一个组件。组件包括对象和Context.
二 Context定义:
语境; 上下文; 背景; 环境
它是一个抽象类.
三 作用
通过实现Context类,可以获取应用程序的资源和类(包括应用级别操作,如启动Activity,发广播,接受Intent等).
类图关系
类图说明
角色 | 类分类 | 作用 |
context | abstract类. | 它有两个具体的实现子类:ContextImpl和ContextWrapper |
ContextWrapper | 包装类 | 调用ContextImpl |
ContextImpl | 实现类 | 真正实现了Context中的所有函数 |
Activity,Application,Service | Activity继承自ContextWrapper的子类ContextThemeWrapper. Application,Service继承自ContextWrapper |
Context 与四大组件的关系
Activity,Service,Application是Context的具体实现子类.
Broadcast Receiver,Content Provider并不是Context的子类,他们所持有的Context都是其他地方传过去的。Context数量=Activity数量+Service数量+1.
四 Context作用域
五 使用
1 如何获取Context
通常我们想要获取Context对象,主要有以下四种方法.
返回值 | 备注 | |
---|---|---|
View.getContext | 当前View对象的Context对象 | 通常是当前正在展示的Activity对象 |
Activity.getApplicationContext | 当前Activity所在的(应用)进程的Context对象 | 使用Context对象时,要优先考虑这个全局的进程Context |
Activity.this | 当前的Activity实例 | 如果是UI控件需要使用Activity作为Context对象,但是默认的Toast实际上使用ApplicationContext也可以。 |
ContextWrapper.getBaseContext() | 获取一个ContextWrapper进行装饰之前的Context | 这个方法在实际开发中使用并不多,也不建议使用。 |
2 代码实现
TextView tv = new TextView(getContext());
ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);getApplicationContext().getSharedPreferences(name, mode);
getApplicationContext().getContentResolver().query(uri, ...);
getContext().getResources().getDisplayMetrics().widthPixels * 5 / 8;
getContext().startActivity(intent);
getContext().startService(intent);
getContext().sendBroadcast(intent);
//获取的是主线程的Looper
new Handler( getContext().getMainLooper() ).post( new Runnable()
{
@Override
public void run()
{
dosomething();
......
}
} );