判断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()
                            }
                        }
                    })

        }
    }

上一篇:项目代码行数统计工具


下一篇:[转]github无需下载进行代码数量统计