Android 轻松获取最上层的Activity

问题描述:开发中我们会遇到需求。需要找到app最上层的Activity,废话不多说,直接上代码。

class MyApp : Application() {

    companion object {
        var topAct: Activity? = null
    }

    override fun onCreate() {
        super.onCreate()
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityPaused(activity: Activity) {
                topAct = null
            }

            override fun onActivityResumed(activity: Activity) {
                topAct = activity as Activity?
            }

            override fun onActivityStarted(activity: Activity) {
            }

            override fun onActivityDestroyed(activity: Activity) {
            }

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

            override fun onActivityStopped(activity: Activity) {
            }

            override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
            }
        })
    }
}

然后在你的代码中使用

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //获取最上层的Activity,做你想做的事情
        val topAct = MyApp.topAct
    }
}

结束,回家吃饭

喜欢的话可以点个赞~

你可能感兴趣的:(Android 轻松获取最上层的Activity)