对Context的理解

Context关于应用环境的全局信息的接口。是一个抽象类,它的实现是由Android系统提供的(其实就是ContextImpl)。有了它可以访问应用特定的资源和类,并且可以发起一些应用层的调用,例如启动activity,广播,或者接收intents

有哪几种Context?

  1. Application
  2. Activity
  3. Service

Application

  1. 继承关系:Application <- ContextWrapper <- Context
  2. 调用顺序:init -> attachBaseContext -> onCreate
  3. ContextWrapper里包含一个Context即mBase,调用都委托给它了

Activity

  1. 继承关系:Activity <- ContextThemeWrapper <- ContextWrapper
  2. 调用顺序:init -> attachBaseContext -> onCreate

Service

  1. 继承关系:Service <- ContextWrapper <- Context
  2. 调用顺序:init -> attachBaseContext -> onCreate

应用里有多少个Context?不同的Context之间有什么区别?

Activity个数+Service个数+Application个数(多进程)
Activity因为要显示UI,所以需要继承ContextThemeWrapper

Activity里的this和getBaseContext有什么区别?

this返回的是Activity对象自己,它继承的是ContextThemeWrapper。而getBaseContext返回的是ContextWrapper里面的mBase

getApplication和getApplicationContext有什么区别?

都是返回Application对象,getApplicationContext是Context的一个抽象方法,getApplication是Activity和Service特有的

应用组件的构造方法,onCreate、attachBaseContext调用顺序?

init -> attachBaseContext -> onCreate

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐