Android5.1.+ getRunningAppProcesses()获取运行中进程(第三方开源库)

版权声明:本文为博主原创文章,允许转载,但转载必须注明出处。 https://blog.csdn.net/DayDayPlayPhone/article/details/52236148

google可能为了安全考虑,在5.1.+后调用activitymanager.getRunningAppProcesses()方法只能返回你自己应用的进程,那如何在5.1.+后获取运行中进程呢?一个大神stackoverflow给出了答案(点击跳转)。如果你能熟练的导入第三方库,那么相信你可以不用向下看了,如果你选择向下看,那我会用白话文教你一步步实现。首先到这位答主的github上下载他上传的开源库,梯子自备(点击跳转)。没有梯子可以到我的个人百度云下载:链接: http://pan.baidu.com/s/1kVjjPsF 密码: ag6u
这里写图片描述
下载完成后解压目录结构
结构
我们只需要其中的红线框住的部分,但是直接导入,肯定会处很多的问题,我们先来处理一部分,打开libsuperuser
这里写图片描述其中你框选的三个文件是我们要注意的。如果要导入的文件中有build.gradle或AndroidManifest.xml、project.properties文件,需要将其用记事本打开后,将里面的gradle及Android版本修改为自己使用的,如果不知道的话可以新建一个工程或者打开以前建的工程中的相关文件进行对比查看。
这里写图片描述
修改完成后来到android studio的project视图下将他粘贴进去
这里写图片描述
粘贴进去肯定会叫你同步,然后就同步罗,会发现一些问题,其中常见的是提示:
Error:(2, 0) Plugin with id ‘com.github.dcendents.android-maven’ not found
Error:(2, 0) Plugin with id ‘com.jfrog.bintray.gradle’ not found
这是因为有两个插件我们没有装上,我们来到Project下,在那个build.grade里面添加全局依赖
这里写图片描述
将这两个依赖的插件写上,建议写一个同步一次分两次进行,第二次下载需要比较长的时间

       //自动化maven打包插件
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
       //自动上传至bintray插件
        classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.0"

填写好后我们会发现没有编译错误了,那我们要怎么去用添加的这个开源库呢??来到android视图下的build.gradle(Module.app)下添加依赖
这里写图片描述

 compile 'eu.chainfire:libsuperuser:1.0.0.+'

重新同步后,我们就可以调用里面的方法了,新建一个ProgressManager类

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;

import java.util.ArrayList;
import java.util.List;

import eu.chainfire.libsuperuser.Shell;

/**
 * @author Jared Rummler
 */
public class ProcessManager {

    private static final String TAG = "ProcessManager";

    private static final String APP_ID_PATTERN;

    static {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            // Android 4.2 (JB-MR1) changed the UID name of apps for multiple user account support.
            APP_ID_PATTERN = "u\\d+_a\\d+";
        } else {
            APP_ID_PATTERN = "app_\\d+";
        }
    }

    public static List<Process> getRunningProcesses() {
        List<Process> processes = new ArrayList<>();
        List<String> stdout = Shell.SH.run("toolbox ps -p -P -x -c");
        for (String line : stdout) {
            try {
                processes.add(new Process(line));
            } catch (Exception e) {
                android.util.Log.d(TAG, "Failed parsing line " + line);
            }
        }
        return processes;
    }

    public static List<Process> getRunningApps() {
        List<Process> processes = new ArrayList<>();
        List<String> stdout = Shell.SH.run("toolbox ps -p -P -x -c");
        int myPid = android.os.Process.myPid();
        for (String line : stdout) {
            try {
                Process process = new Process(line);
                if (process.user.matches(APP_ID_PATTERN)) {
                    if (process.ppid == myPid || process.name.equals("toolbox")) {
                        // skip the processes we created to get the running apps.
                        continue;
                    }
                    processes.add(process);
                }
            } catch (Exception e) {
                android.util.Log.d(TAG, "Failed parsing line " + line);
            }
        }
        return processes;
    }

    public static class Process implements Parcelable {

        /** User name */
        public final String user;

        /** User ID */
        public final int uid;

        /** Processes ID */
        public final int pid;

        /** Parent processes ID */
        public final int ppid;

        /** virtual memory size of the process in KiB (1024-byte units). */
        public final long vsize;

        /** resident set size, the non-swapped physical memory that a task has used (in kiloBytes). */
        public final long rss;

        public final int cpu;

        /** The priority */
        public final int priority;

        /** The priority, <a href="https://en.wikipedia.org/wiki/Nice_(Unix)">niceness</a> level */
        public final int niceness;

        /** Real time priority */
        public final int realTimePriority;

        /** 0 (sched_other), 1 (sched_fifo), and 2 (sched_rr). */
        public final int schedulingPolicy;

        /** The scheduling policy. Either "bg", "fg", "un", "er", or "" */
        public final String policy;

        /** address of the kernel function where the process is sleeping */
        public final String wchan;

        public final String pc;

        /**
         * Possible states:
         * <p/>
         * "D" uninterruptible sleep (usually IO)
         * <p/>
         * "R" running or runnable (on run queue)
         * <p/>
         * "S" interruptible sleep (waiting for an event to complete)
         * <p/>
         * "T" stopped, either by a job control signal or because it is being traced
         * <p/>
         * "W" paging (not valid since the 2.6.xx kernel)
         * <p/>
         * "X" dead (should never be seen)
         * </p>
         * "Z" defunct ("zombie") process, terminated but not reaped by its parent
         */
        public final String state;

        /** The process name */
        public final String name;

        /** user time in milliseconds */
        public final long userTime;

        /** system time in milliseconds */
        public final long systemTime;

        // Much dirty. Much ugly.
        private Process(String line) throws Exception {
            String[] fields = line.split("\\s+");
            user = fields[0];
            uid = android.os.Process.getUidForName(user);
            pid = Integer.parseInt(fields[1]);
            ppid = Integer.parseInt(fields[2]);
            vsize = Integer.parseInt(fields[3]) * 1024;
            rss = Integer.parseInt(fields[4]) * 1024;
            cpu = Integer.parseInt(fields[5]);
            priority = Integer.parseInt(fields[6]);
            niceness = Integer.parseInt(fields[7]);
            realTimePriority = Integer.parseInt(fields[8]);
            schedulingPolicy = Integer.parseInt(fields[9]);
            if (fields.length == 16) {
                policy = "";
                wchan = fields[10];
                pc = fields[11];
                state = fields[12];
                name = fields[13];
                userTime = Integer.parseInt(fields[14].split(":")[1].replace(",", "")) * 1000;
                systemTime = Integer.parseInt(fields[15].split(":")[1].replace(")", "")) * 1000;
            } else {
                policy = fields[10];
                wchan = fields[11];
                pc = fields[12];
                state = fields[13];
                name = fields[14];
                userTime = Integer.parseInt(fields[15].split(":")[1].replace(",", "")) * 1000;
                systemTime = Integer.parseInt(fields[16].split(":")[1].replace(")", "")) * 1000;
            }
        }

        private Process(Parcel in) {
            user = in.readString();
            uid = in.readInt();
            pid = in.readInt();
            ppid = in.readInt();
            vsize = in.readLong();
            rss = in.readLong();
            cpu = in.readInt();
            priority = in.readInt();
            niceness = in.readInt();
            realTimePriority = in.readInt();
            schedulingPolicy = in.readInt();
            policy = in.readString();
            wchan = in.readString();
            pc = in.readString();
            state = in.readString();
            name = in.readString();
            userTime = in.readLong();
            systemTime = in.readLong();
        }

        public String getPackageName() {
            if (!user.matches(APP_ID_PATTERN)) {
                // this process is not an application
                return null;
            } else if (name.contains(":")) {
                // background service running in another process than the main app process
                return name.split(":")[0];
            }
            return name;
        }

        public PackageInfo getPackageInfo(Context context, int flags)
                throws PackageManager.NameNotFoundException
        {
            String packageName = getPackageName();
            if (packageName == null) {
                throw new PackageManager.NameNotFoundException(name + " is not an application process");
            }
            return context.getPackageManager().getPackageInfo(packageName, flags);
        }

        public ApplicationInfo getApplicationInfo(Context context, int flags)
                throws PackageManager.NameNotFoundException
        {
            String packageName = getPackageName();
            if (packageName == null) {
                throw new PackageManager.NameNotFoundException(name + " is not an application process");
            }
            return context.getPackageManager().getApplicationInfo(packageName, flags);
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(user);
            dest.writeInt(uid);
            dest.writeInt(pid);
            dest.writeInt(ppid);
            dest.writeLong(vsize);
            dest.writeLong(rss);
            dest.writeInt(cpu);
            dest.writeInt(priority);
            dest.writeInt(niceness);
            dest.writeInt(realTimePriority);
            dest.writeInt(schedulingPolicy);
            dest.writeString(policy);
            dest.writeString(wchan);
            dest.writeString(pc);
            dest.writeString(state);
            dest.writeString(name);
            dest.writeLong(userTime);
            dest.writeLong(systemTime);
        }

        public static final Creator<Process> CREATOR = new Creator<Process>() {

            public Process createFromParcel(Parcel source) {
                return new Process(source);
            }

            public Process[] newArray(int size) {
                return new Process[size];
            }
        };
    }

}

通过这个类我们就可以获得运行中的进程了

//获取运行中进程
 List<ProcessManager.Process> runningProcesses = ProcessManager.getRunningProcesses();

但是有很多进程都没有名字,如果你想让用户直观的管理进程的话可能需要下面这个循环过滤没有名字的线程

 List<ProcessManager.Process> Processes=new ArrayList<>();
 PackageManager pm = getPackageManager();
 runningProcesses = ProcessManager.getRunningProcesses();
 for (ProcessManager.Process runningProcesse : runningProcesses) {
      String packname = runningProcesse.getPackageName();
            try {
                ApplicationInfo applicationInfo = pm.getApplicationInfo(packname, 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                continue;
            }
            Processes.add(runningProcesse);
        }

我的博客网站:http://huyuxin.top/欢迎大家访问!评论!

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页