ApplicationContext和Context

1. 当使用 LayoutInflater 从 xml 文件中 inflate 布局时,调用的是 View(Context,AttributeSet) 构造函数,使用的 Context 实例跟 LayoutInflater 创建时使用的 Context 一样,并且 LayoutInflater 会缓存在 Context 实例中,即相同的 Context 实例多次调用会获取一样的 LayoutInflater 实例。

2. Activity Context 会读取 Theme 的样式信息,而 Application Context 则不会。

getApplicationContext() 的存在是 Android 历史原因,getApplication() 这个只存在 Activity 和 Service 类中,那么对于 BroadcastReceiver 和 ContentProvider 来说,要获取 Application,就只能通过 getApplicationContext()。

1.对于 Activity/Service 来说,这两个方法没有区别,除非厂商修改过

2.BroadcastReceiver 只能通过 getApplicationContext() 获取 Application 实例

3.ContentProvider 也只能通过 getApplicationContext() 获取 Application 实例,但有可能出现空值的情况。当同个进程有多个 apk 的情况下,对于第二个 apk 是由 provider 方式拉起,而 provider 创建过程中并不会初始化 Application,此时调用 getApplicationContext() 则会返回空。

猜你喜欢

转载自blog.csdn.net/m0_38058826/article/details/82385377