首页 > 移动平台 > 详细

Android 获取服务是否在后台 & 获取TopActivity

时间:2021-08-30 09:18:24      阅读:10      评论:0      收藏:0      [点我收藏+]
ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceName.equals(service.service.getClassName())) {
return true;
}
}

PS:
serviceName 服务名称(完整的服务名称,包括包名,如com.xxx.xxxService)



/**
* 5.0以上版本
* 需要使用系统签名,同时需要<uses-permission android:name="android.permission.DUMP"/>或声明系统用户
*
*/
public static ComponentName getTopActivity_L_U() {
String cmd = "dumpsys activity activities | grep mResumedActivity";//"dumpsys activity";
String pkgName = "";
String className = "";
String s = "";
ComponentName result = null;
Process p = null;
try {
p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
if (line.contains("mResumedActivity")) {
s = line;
break;
}
}
if (CommonUtil.isNotEmpty(s)) {
String info = s.substring(s.indexOf("u0 ") + 3, s.lastIndexOf(" "));
pkgName = info.split("/")[0];

className = info.split("/")[1];
if (className.startsWith(".")) {
className = pkgName + className;
}

if (CommonUtil.isNotEmpty(pkgName) && CommonUtil.isNotEmpty(className)) {
result = new ComponentName(pkgName, className);
}
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
p.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;

}

/**
* 5.0以下版本
*
* @param context
* @return
*/
public static ComponentName getTopActivity_L_D(Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
return cn;
}

Android 获取服务是否在后台 & 获取TopActivity

原文:https://www.cnblogs.com/mengdao/p/15201932.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!