Checking if an Android application is running in the background

前端 未结 30 2799
无人共我
无人共我 2020-11-21 06:19

By background, I mean none of the application\'s activities are currently visible to the user?

30条回答
  •  鱼传尺愫
    2020-11-21 06:55

    None of the answers quite fitted the specific case if you're looked to know if a specfic activity is in the forground and if you're an SDK without direct access to the Application. For me I was in background thread having just recieved a push notification for a new chat message and only want to display a system notification if the chat screen isn't in the foreground.

    Using the ActivityLifecycleCallbacks that as been recommended in other answers I've created a small util class that houses the logic to whether MyActivity is in the Foreground or not.

    class MyActivityMonitor(context: Context) : Application.ActivityLifecycleCallbacks {
    
    private var isMyActivityInForeground = false
    
    init {
        (context.applicationContext as Application).registerActivityLifecycleCallbacks(this)
    }
    
    fun isMyActivityForeground() = isMyActivityInForeground
    
    override fun onActivityPaused(activity: Activity?) {
        if (activity is MyActivity) {
            isMyActivityInForeground = false
        }
    }
    
    override fun onActivityResumed(activity: Activity?) {
        if (activity is MyActivity) {
            isMyActivityInForeground = true
        }
    }
    

    }

提交回复
热议问题