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


    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;
    }
  • 相关阅读:
    软件开发中的程序员和产品经理
    Linux下自动备份MySQL
    使用FeignClient,消费方使用方法,和一些坑
    FeignClient 使用
    关于sql查询,按时间段查询
    aquery验证
    Ajax
    弹框
    来源于网络 感觉很好就收藏;了
    org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
  • 原文地址:https://www.cnblogs.com/mengdao/p/15201932.html
Copyright © 2020-2023  润新知