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()方法的访问权限,只允许获取当前应用的进程信息,而不允许获取其他应用或系统进程的信息.
相关推荐
ŧ榕树先生1 小时前
稳定的Android studio版本安装教程
android·ide·android studio
早上好啊! 树哥1 小时前
常见的文件加密方式之【异或加密】,代入原理看例子,帮助更好的理解。
android·java·junit
沅霖3 小时前
Android: Handler 的用法详解
android
鸿蒙布道师3 小时前
鸿蒙NEXT开发数值工具类(TS)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
Yang-Never5 小时前
Open GL ES ->GLSurfaceView在正交投影下的图片旋转、缩放、位移
android·开发语言·kotlin·android studio·贴图
粤M温同学5 小时前
使用Android 原生LocationManager获取经纬度
android
stevenzqzq5 小时前
Android Hilt 教程
android
CYRUS_STUDIO5 小时前
Frida Stalker Trace 指令跟踪&寄存器变化监控
android·逆向·汇编语言
bst@微胖子5 小时前
Flutter之设计与主题&字体
android·flutter
深圳之光7 小时前
增加android 禁用相机后摄的接口
android·数码相机