其他分享
首页 > 其他分享> > 判断App是否正在运行。极光推送的时候要判断的

判断App是否正在运行。极光推送的时候要判断的

作者:互联网

    private fun isAppRunning(context: Context): Boolean {
        val packageName = context.packageName
        val topActivityClassName = getTopActivityName(context)
        return if (packageName != null && topActivityClassName != null && topActivityClassName.startsWith(
                packageName
            )
        ) {
            true
        } else {
            false
        }
    }

    fun getTopActivityName(context: Context): String? {
        var topActivityClassName: String? = null
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningTaskInfos: List<ActivityManager.RunningTaskInfo>? =
            activityManager.getRunningTasks(1)
        if (runningTaskInfos != null) {
            val f: ComponentName? = runningTaskInfos[0].topActivity
            if (f != null) {
                topActivityClassName = f.getClassName()
            }
        }
        return topActivityClassName
    }

如果是已经运行了 可以直接执行逻辑 没有执行 可以通过打开主页3s后执行逻辑

    fun startByForground(context: Context, startFunction: () -> Unit) {
        //前台运行直接打开。
        val runForeground = isAppRunning(context);
        Logger.e(TAG, "runForeground" + runForeground)
        if (runForeground) {
            startFunction()
        } else {
            //后台运行稍后打开
            ARouter.getInstance().build(RouterConstants.MAIN)
                .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .navigation(context,
                    object : NavigationCallback() {
                        override fun onArrival(postcard: Postcard) {

                            Timer().schedule(3000) { //执行的任务
                                startFunction()
                            }
                        }
                    })

        }
    }

标签:判断,Context,val,App,null,context,topActivityClassName,推送,packageName
来源: https://blog.csdn.net/mp624183768/article/details/121205883