Android获取当前进程名

Android获取当前进程名,俩种方式,第一种通过读取 /proc/self/cmdline 文件的内容,代码如下:

    /**
     * 返回当前的进程名
     */
    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;
    }

第二种,通过反射调用ActivityThread中的 getProcessName() 方法拿到进程名,代码如下

    /**
     * 返回当前的进程名
     */
    public static String getCurrentProcessName()throws Exception {

        //1. 通过ActivityThread中的currentActivityThread()方法得到ActivityThread的实例对象
        Class activityThreadClass = Class.forName("android.app.ActivityThread");
        Method method = activityThreadClass.getDeclaredMethod("currentActivityThread", activityThreadClass);
        Object activityThread = method.invoke(null);

        //2. 通过activityThread的getProcessName() 方法获取进程名
        Method getProcessNameMethod = activityThreadClass.getDeclaredMethod("getProcessName", activityThreadClass);
        Object processName = getProcessNameMethod.invoke(activityThread);

        return processName.toString();
    }

 

你可能感兴趣的:(工作常用)