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()方法的访问权限,只允许获取当前应用的进程信息,而不允许获取其他应用或系统进程的信息.
相关推荐
OkeyProxy4 小时前
設置Android設備全局代理
android·代理模式·proxy模式·代理服务器·海外ip代理
刘志辉4 小时前
vue传参方法
android·vue.js·flutter
前期后期7 小时前
Android OkHttp源码分析(一):为什么OkHttp的请求速度很快?为什么可以高扩展?为什么可以高并发
android·okhttp
轻口味9 小时前
Android应用性能优化
android
全职计算机毕业设计9 小时前
基于 UniApp 平台的学生闲置物品售卖小程序设计与实现
android·uni-app
dgiij10 小时前
AutoX.js向后端传输二进制数据
android·javascript·websocket·node.js·自动化
SevenUUp11 小时前
Android Manifest权限清单
android
高林雨露11 小时前
Android 检测图片抓拍, 聚焦图片后自动完成拍照,未对准图片的提示请将摄像头对准要拍照的图片
android·拍照抓拍
wilanzai11 小时前
Android View 的绘制流程
android
INSBUG12 小时前
CVE-2024-21096:MySQLDump提权漏洞分析
android·adb