美文网首页already
什么是Context

什么是Context

作者: hao_developer | 来源:发表于2022-05-09 17:16 被阅读0次

获取当前Activity最主要的作用当然是为了能随时获取Context

什么是Context

源码中的注释是这么来解释Context的:Context提供了关于应用环境全局信息的接口。Context到底可以实现哪些功能呢?弹出Toast、启动Activity、启动Service、发送广播、操作数据库等等都需要用到Context


image.png

如何获取当前Activity

创建一个Activity管理类,通过在Application监听所有Activity的生命周期回调来获取当前Activity。以下是具体代码:
首先创建Activity管理类(object声明相当于单例)

object ActivityManager {
    // 弱引用
    private var sCurrentActivityWeakRef: WeakReference<Activity>? = null

    fun getCurrentActivity(): Activity? = sCurrentActivityWeakRef?.get()

    fun setCurrentActivity(activity: Activity) {
        sCurrentActivityWeakRef = WeakReference(activity)
    }
}

创建Application,并监听所有Activity的生命周期回调,并在androidmanifest.xml中注册

class WeatherApplication : Application() {
    // 单例
    companion object {
        fun getInstance(): WeatherApplication = Inner.instance
    }

    private object Inner {
        lateinit var instance: WeatherApplication
    }

    override fun onCreate() {
        super.onCreate()
        Inner.instance = this

        // 监听所有Activity的生命周期回调
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            }

            override fun onActivityStarted(activity: Activity) {
            }

            override fun onActivityResumed(activity: Activity) {
                // 在此处设置当前的Activity
                ActivityManager.setCurrentActivity(activity)
            }

            override fun onActivityPaused(activity: Activity) {
            }

            override fun onActivityStopped(activity: Activity) {
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
            }
        })

    }
}

通过ActivityManager.getCurrentActivity()获取栈顶(当前)Activity

相关文章

网友评论

    本文标题:什么是Context

    本文链接:https://www.haomeiwen.com/subject/gbwhurtx.html