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()方法的访问权限,只允许获取当前应用的进程信息,而不允许获取其他应用或系统进程的信息.
相关推荐
优雅的潮叭3 小时前
cud编程之 reduce
android·redis·缓存
2601_949613023 小时前
flutter_for_openharmony家庭药箱管理app实战+用药知识详情实现
android·javascript·flutter
一起养小猫3 小时前
Flutter for OpenHarmony 实战 表单处理与验证完整指南
android·开发语言·前端·javascript·flutter·harmonyos
2601_949975084 小时前
flutter_for_openharmony城市井盖地图app实战+附近井盖实现
android·flutter
倾云鹤4 小时前
通用Digest认证
android·digest
我是阿亮啊4 小时前
Android 自定义 View 完全指南
android·自定义·自定义view·viewgroup
2601_949833396 小时前
flutter_for_openharmony口腔护理app实战+意见反馈实现
android·javascript·flutter
峥嵘life6 小时前
Android 16 EDLA测试STS模块
android·大数据·linux·学习
TheNextByte16 小时前
如何打印Android手机联系人?
android·智能手机
泡泡以安7 小时前
Android 逆向实战:从零突破某电商 App 登录接口全参数加密
android·爬虫·安卓逆向