Android ApplicationContext接口深入分析

需求

Android(Kotlin)获取应用全局上下文 ApplicationContext。

希望可以在应用内任意位置获取上下文,而不是仅在 Activity 或 Service 里才能获取。

ApplicationContext 是和应用全局相关的。

实现方法

  • 自定义 MyApplication,保存自身的 Application 实例。
  • MyApplication 配置到 AndroidManifest 中。
  • 定义顶层属性 appContext,获取 Application 实例的applicationContext。

代码

package com.example.fileio
import android.app.Application
/**
 * 自定义 Application
 */
class MyApplication : Application() {
 companion object {
 lateinit var application: Application
 }
 init {
 application = this
 }
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools">
 <application
 android:name=".MyApplication"
 </application>
</manifest>

上下文工具类 ContextUtil.kt

package com.example.fileio.util
import android.content.Context
import com.example.fileio.MyApplication
val appContext: Context = MyApplication.application.applicationContext

调用

可以在应用内任意位置获取 ApplicationContext。

Application

用于维护全局应用程序状态的基类。

Application | Android Developers (google.cn)

getApplicationContext()

返回当前进程的单个全局Application对象的上下文。

当需要一个生命周期与当前上下文分离的上下文时,才应该使用该上下文。

该上下文与进程的生命周期关联,而不是与当前组件相关联。

参考

作者:宋冠巡原文地址:https://blog.csdn.net/sgx1825192/article/details/127885808

%s 个评论

要回复文章请先登录注册