1.在AndroidManifest中加入权限
<uses-permission android:name="android.permission.GET_TASKS"/>
2.Kotlin方法
/**
* 判断某个Activity是否在前台
*
* @param context Context
* @param className 界面的类名
* @return 是否在前台显示
*/
public fun isForeground(context: Context?, className: String):Boolean {
if (context == null || TextUtils.isEmpty(className)) return false
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val list = am.getRunningTasks(10)
if (list != null && list.size > 0) {
val cpn = list[0].topActivity
if (className == cpn.className) return true
}
return false
}