一、什么是Context?
Context
是一个抽象基类。在翻译为上下文,是提供一些程序的运行环境基础信息。
Context
下有两个子类,ContextWrapper
是上下文功能的封装类(起到方法传递的作用,主要实现还是ContextImpl),而ContextImpl
则是上下文功能的实现类。
ContextWrapper
又有三个直接的子类,ContextThemeWrapper
、Service
和Application
。其中,ContextThemeWrapper
是一个带主题的封装类,所说的主题就是指在AndroidManifest.xml中通过android:theme为Application元素或者Activity元素指定的主题,而它有一个直接子类就是Activity
,所以Activity
和Service
以及Application
的Context是不一样的,只有Activity需要主题,Service不需要主题。
其中最核心的类就是ContextImpl类。ContextImpl类继承了抽象类Context并且实现所有的抽象方法,并且自身还实现了很多get,create,check开头的方法。
在我们的实际开发中,context会被大量的使用到,例如startActivity,访问资源,toast弹出,dialog,启动service,发送广播等等。
TextView tv = new TextView(getContext());
ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
AudioManager am = (AudioManager)
getApplicationContext().getContentResolver().query(uri, ...);
getContext().getResources().getDisplayMetrics().widthPixels * 5 / 8;
getContext().startActivity(intent);
getContext().startService(intent);
getContext().sendBroadcast(intent);
一个应用