检查活动是否正在从服务运行 [英] Check if Activity is running from Service

查看:28
本文介绍了检查活动是否正在从服务运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Service 如何检查它的应用程序之一的 Activity 是否在前台运行?

How can a Service check if one of it's application's Activity is running in foreground?

推荐答案

使用下面的方法和你的包名.如果您的任何活动处于前台,它将返回 true.

Use the below method with your package name. It will return true if any of your activities is in foreground.

public boolean isForeground(String myPackage) {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1); 
    ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
    return componentInfo.getPackageName().equals(myPackage);
}

更新:

添加权限:

Update:

Add Permission:

<uses-permission android:name="android.permission.GET_TASKS" />

这篇关于检查活动是否正在从服务运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆