Android 获取进程名称

Android 获取进程名称

本篇文章主要获取下当前应用的进程名称,具体代码如下:

java 复制代码
public static String getProcessNameDevice(final Context context) {
    int myPid = Process.myPid();
    if (context == null || myPid <= 0) {
        return "";
    }

    ActivityManager.RunningAppProcessInfo myProcess = null;
     // 获取ActivityManager
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

    if (activityManager != null) {
        // 获取正在运行的进程列表
        List<ActivityManager.RunningAppProcessInfo> appProcessList = activityManager.getRunningAppProcesses();
        if (appProcessList != null) {
            try {
                // 遍历进程列表,获取进程名
                for (ActivityManager.RunningAppProcessInfo process : appProcessList) {
                    if (process.pid == myPid) {
                        myProcess = process;
                        break;
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "getProcessNameInternal exception:" + e.getMessage());
            }

            if (myProcess != null) {
                return myProcess.processName;
            }
        }
    }

    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;
        }
        return new String(buffer, 0, len, Charset.forName("UTF-8"));
    } catch (Throwable e) {
        throw new AssertionError(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

需要注意:

  1. 自Android 5.1版本开始,Google限制了对getRunningAppProcesses()方法的访问权限,只允许获取当前应用的进程信息,而不允许获取其他应用或系统进程的信息.
相关推荐
xuankuxiaoyao20 分钟前
Zygisk-LSPosed 模块完整作用说明
android
YXL1111YXL33 分钟前
ViewModel 底层原理
android
阿pin42 分钟前
Android随笔-APP首次启动流程
android·application·activity
阿pin1 小时前
Android随笔-SELinux是什么?
android·selinux
红糖奶茶1 小时前
设备管理器中Android出现黄色感叹号怎么办? 如何修复?
android
取个名字太难了~1 小时前
从通用到专用:影像 SDK 的场景化封装与垂直行业落地实践
android·数码相机·美颜·相机连接·demu
zakariyaa331 小时前
Android 绘制调度机制
android·gitee
安卓修改大师1 小时前
安卓修改大师Smali语法实战:从零掌握数据类型、判断循环、自定义方法与Toast插桩
android
私人珍藏库1 小时前
[Android] 多开空间-一机多账号+应用一键克隆双开
android·人工智能·智能手机·软件
海兰2 小时前
【SpringBoot 】AOP企业级权限控制方案(二)
android·java·spring boot