美文网首页Android
Android获取进程名

Android获取进程名

作者: 眼角的伤痕 | 来源:发表于2019-02-11 15:41 被阅读1次

    由于项目中涉及到多进程的原因,需要判断当前所属的进程,因此需要获取进程名,在网上搜罗了好多种获取进程名的方法,试了一下有以下两种能够正确获取当前进程的进程名:

    • 利用Linux系统获取进程名
     public static String getCurrentProcessName() {
            FileInputStream in = null;
            try {
                String fn = "/proc/self/cmdline";
                in = new FileInputStream(fn);
                byte[] buffer = new byte[256];
                int len = 0;
                int b;
                while ((b = in.read()) > 0 && len < buffer.length) {
                    buffer[len++] = (byte) b;
                }
                if (len > 0) {
                    String s = new String(buffer, 0, len, "UTF-8");
                    return s;
                }
            } catch (Throwable e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }
    
    • 利用Android系统获取进程名
       public static String getProcessName(Context cxt) {
            int pid = android.os.Process.myPid();
            ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
            if (runningApps == null) {
                return null;
            }
            for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
                if (procInfo.pid == pid) {
                    return procInfo.processName;
                }
            }
            return null;
        }
    

    以上这两种方法能够正确获取当前进程名,还有一种通过反射获取进程名的方法,我试了一下,没有成功获取进程名。

       public static String getProcessName(Context cxt) {
            int pid = android.os.Process.myPid();
            ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
            if (runningApps == null) {
                return null;
            }
            for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
                if (procInfo.pid == pid) {
                    return procInfo.processName;
                }
            }
            return null;
        }
    

    相关文章

      网友评论

        本文标题:Android获取进程名

        本文链接:https://www.haomeiwen.com/subject/nryqeqtx.html