Android: How can I get the current foreground activity (from a service)?

前端 未结 12 1937
北恋
北恋 2020-11-22 07:53

Is there a native android way to get a reference to the currently running Activity from a service?

I have a service running on the background, and I would like to up

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 08:21

    Here's what I suggest and what has worked for me. In your application class, implement an Application.ActivityLifeCycleCallbacks listener and set a variable in your application class. Then query the variable as needed.

    class YourApplication: Application.ActivityLifeCycleCallbacks {
        
        var currentActivity: Activity? = null
    
        fun onCreate() {
            registerActivityLifecycleCallbacks(this)
        }
    
        ...
        
        override fun onActivityResumed(activity: Activity) {
            currentActivity = activity
        }
    }
    

提交回复
热议问题