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()方法的访问权限,只允许获取当前应用的进程信息,而不允许获取其他应用或系统进程的信息.
相关推荐
冬奇Lab10 小时前
PowerManagerService(下):Doze模式与电池优化
android·源码阅读
砖厂小工12 小时前
Compose 中函数引用 vs Lambda:到底该用哪个?
android
Kapaseker1 天前
详解 Compose background 的重组陷阱
android·kotlin
黄林晴1 天前
Kotlin 2.3.20-RC2 来了!JPA 开发者狂喜,6 大更新一文速览
android·kotlin
kymjs张涛2 天前
OpenClaw 学习小组:初识
android·linux·人工智能
范特西林2 天前
实战演练——从零实现一个高性能 Binder 服务
android
范特西林2 天前
代码的生成:AIDL 编译器与 Parcel 的序列化艺术
android
范特西林2 天前
深入内核:Binder 驱动的内存管理与事务调度
android
范特西林2 天前
解剖麻雀:Binder 通信的整体架构全景图
android
范特西林2 天前
破冰之旅:为什么 Android 选择了 Binder?
android