Android 把后台应用切换到前台

1、判断当前应用是否在前台

private fun isForeground(context: Context): Boolean {
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val tasks = am.getRunningTasks(1)
        if (tasks != null && !tasks.isEmpty()) {
            val topActivity = tasks[0].topActivity
            if (topActivity.packageName == context.packageName) {
                return true
            }
        }
        return false
    }

2、把当前应用切换到前台

private fun moveTaskToFront() {
        val mAm = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        //获得当前运行的task
        val taskList = mAm.getRunningTasks(100)
        for (rti in taskList) {
            //找到当前应用的task,并启动task的栈顶activity,达到程序切换到前台
            if (rti.topActivity.packageName == context.packageName) {
                mAm.moveTaskToFront(rti.id, 0)
                return
            }
        }
    }

3、添加权限


    
    
    
    

 

你可能感兴趣的:(Android 把后台应用切换到前台)