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();    }

 

更多相关文章

  1. 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
  2. 一款霸榜 GitHub 的开源 Linux 资源监视器!
  3. android 源代码版本号整理
  4. android webView 使用方法
  5. Android(安卓)生命周期架构组件使用方法
  6. android彻底杀死当前activity和线程方法
  7. android 如何判断开机完成
  8. Android获取屏幕大小 .
  9. Android屏幕适配大法

随机推荐

  1. 循环题目
  2. 招投标IT项目怎么知道是否赚钱?
  3. 应届网工毕业生该如何斩获心仪offer?面试
  4. MiniRDS空间扩容
  5. 怎么区别项目 项目集 项目组合管理?
  6. 软件项目怎么快速响应用户需求
  7. Redis高可用集群搭建,配置,运维与应用!
  8. 给SFTP添加访问记录
  9. juniper-SRX FW ssh登录被拒绝问题
  10. 项目管理神书---PMP认证官方教材PMBOK