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()方法的访问权限,只允许获取当前应用的进程信息,而不允许获取其他应用或系统进程的信息.
相关推荐
用户2018792831671 小时前
Binder 同应用内(本地)通信是否存在 1MB 大小限制?
android
一条上岸小咸鱼1 小时前
Kotlin 基本数据类型(四):String
android·前端·kotlin
Onion_992 小时前
学习下Github上的Android CICD吧
android·github
来来走走3 小时前
Flutter Form组件的基本使用
android·flutter
顾林海3 小时前
Android MMKV 深度解析:原理、实践与源码剖析
android·面试·源码阅读
雨白4 小时前
TCP/IP 核心概念详解:从网络分层到连接管理
android
Wgllss5 小时前
雷电雨效果:Kotlin+Compose+协程+Flow 实现天气UI
android·架构·android jetpack
用户207038619497 小时前
Compose 可点击文本:ClickableText Compose 中的 ClickableSpan
android
常利兵7 小时前
Kotlin作用域函数全解:run/with/apply/let/also与this/it的魔法对决
android·开发语言·kotlin
幼稚园的山代王7 小时前
Kotlin-基础语法练习一
android·开发语言·kotlin