Judge whether the source code of voice dating software is in the foreground or background in Android

brief introduction
Sometimes we need to judge whether the source code of voice dating software is in the foreground or background, which is helpful for us to deal with some business
Here is how to judge whether the voice dating software source code is in the foreground or background
Through RunningTasks, RunningProcess and activitylifecycle callbacks respectively

realization
RunningTasks

 private fun getTopApplication() {

        //Get the ActivityManager first
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

        if (activityManager.getRunningTasks(1) == null) {
            Log.e(TAG, "getForegroundActivity: ")
            return
        }

        var runningTaskInfo = activityManager.getRunningTasks(1)[0]
        if (runningTaskInfo == null) {
            Log.e(TAG, "runningTaskInfo is null")
            return
        }

        runningTaskInfo.topActivity?.let {
            Log.e(TAG, "top application is ${it.packageName}")
        }
    }

The getRunningTask method has been abandoned above 5.0. It will only return some insensitive tasks of itself and the system, and will not return the tasks of other applications. Using this method to judge whether the source code of voice dating software is in the background is still valid, but it is unable to judge whether other applications are in the foreground, because information can no longer be obtained.

RunningProcess

/**
     * Judge whether the current application is in the foreground
     */
    private fun isAppForeground(): Boolean {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        /**
         * Surviving App processes
         */
        var runningAppProcesses = activityManager.runningAppProcesses

        if (runningAppProcesses == null) {
            Log.e(TAG, "runningAppProcesses is null")
            return false
        }

        runningAppProcesses.forEach {
            if (it.processName == packageName && (it.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)) {
                return true
            }
        }
        return false
    }
 /**
     * Used to determine which application is in the foreground
     */
    private fun getForegroundApp(): String? {

        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        var runningAppProcesses = activityManager.runningAppProcesses
        if (runningAppProcesses.isNullOrEmpty()) {
            return null
        }

        runningAppProcesses.forEach {

            if (it.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND || it.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
                return it.processName
            }
        }

        return null
    }

Android5. It has been abandoned since 0.

In the source code of voice dating software, you often need to stay in the background to continuously obtain server messages, so you need to set the Service to START_STICKY, after kill ing, it will be restarted (wait for about 5s) to ensure that the Service is resident in the background. If the Service sets this attribute, the process of the source code of the voice dating software will be judged as the foreground. The code is represented as

appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND

The above code is always true, so you can never judge which is the front desk.

ActivityLifecycleCallbacks
Here, we encapsulate the implementation class of ActivityLifecycleCallbacks and use high-order functions to provide callback processing through high-order functions when we need to implement the callback of the declaration cycle. Otherwise, no processing will be done by default

class MyActivityLifecycleCallbacks(
    var onActivityCreatedAction: ((Activity, Bundle?) -> Unit)? = null,
    var onActivityStartedAction: ((Activity) -> Unit)? = null,
    var onActivityResumedAction: ((Activity) -> Unit)? = null,
    var onActivityPausedAction: ((Activity) -> Unit)? = null,
    var onActivityStoppedAction: ((Activity) -> Unit)? = null,
    var onActivitySaveInstanceStateAction: ((Activity, Bundle) -> Unit)? = null,
    var onActivityDestroyedAction: ((Activity) -> Unit)? = null

) : Application.ActivityLifecycleCallbacks {

    private var mCount=0
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        onActivityCreatedAction?.invoke(activity, savedInstanceState)
    }

    override fun onActivityStarted(activity: Activity) {
        mCount++
        onActivityStartedAction?.invoke(activity)
    }

    override fun onActivityResumed(activity: Activity) {
        onActivityResumedAction?.invoke(activity)
    }

    override fun onActivityPaused(activity: Activity) {
        onActivityPausedAction?.invoke(activity)
    }

    override fun onActivityStopped(activity: Activity) {
        mCount--
        onActivityStoppedAction?.invoke(activity)
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        onActivitySaveInstanceStateAction?.invoke(activity, outState)
    }

    override fun onActivityDestroyed(activity: Activity) {
        onActivityDestroyedAction?.invoke(activity)
    }

    /**
     * Here we return the actual value of mCount
     */
    fun getCount():Int = mCount
}

Then we register in onCreate of Application

class LifeApplication : Application() {

    private val TAG = "LifeApplication"

    private val mActivityLifecycleCallbacks by lazy {
        MyActivityLifecycleCallbacks(
            onActivityCreatedAction = { activit, bundle ->
                Log.e(TAG, "onCreate: ")


            },
            onActivityStoppedAction = { activity ->

                Log.e(TAG, "onStop ")

            },
            onActivityDestroyedAction = { activity ->
                Log.e(TAG, "onDestroy")

            })
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        //Register lifecycle callback events
        registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks)
    }

    /**
     * Used to determine whether the current process is in the foreground
     */
    fun isForegroundMethod(): Boolean = mActivityLifecycleCallbacks.getCount() > 0


    companion object{
        private  var  instance :LifeApplication?= null
        fun getInstance () = instance!!
    }

When we click either the Back key or the Home key, we will call Back to the onStop method. We add and subtract the mCount value in onStart and onStop respectively
In this way, we can judge whether the current voice dating software source code is in the foreground or background through this value

This article is reprinted from the network. It is reprinted only to share dry goods knowledge. If there is infringement, please contact yunbao technology for deletion
Original link: https://www.jianshu.com/p/a326ee3c582e

Added by Maknis on Sun, 23 Jan 2022 01:29:53 +0200