Android获取当前进程名
16lz
2021-01-25
Android获取当前进程名,俩种方式,第一种通过读取 /proc/self/cmdline 文件的内容,代码如下:
/** * 返回当前的进程名 */ public static String getCurrentProcessName() { 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; } if (len > 0) { String s = new String(buffer, 0, len, "UTF-8"); return s; } } catch (Throwable e) { e.printStackTrace(); } finally { if (in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }
第二种,通过反射调用ActivityThread中的 getProcessName() 方法拿到进程名,代码如下
/** * 返回当前的进程名 */ public static String getCurrentProcessName()throws Exception { //1. 通过ActivityThread中的currentActivityThread()方法得到ActivityThread的实例对象 Class<?> activityThreadClass = Class.forName("android.app.ActivityThread"); Method method = activityThreadClass.getDeclaredMethod("currentActivityThread", activityThreadClass); Object activityThread = method.invoke(null); //2. 通过activityThread的getProcessName() 方法获取进程名 Method getProcessNameMethod = activityThreadClass.getDeclaredMethod("getProcessName", activityThreadClass); Object processName = getProcessNameMethod.invoke(activityThread); return processName.toString(); }
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- 一款霸榜 GitHub 的开源 Linux 资源监视器!
- android 源代码版本号整理
- android webView 使用方法
- Android(安卓)生命周期架构组件使用方法
- android彻底杀死当前activity和线程方法
- android 如何判断开机完成
- Android获取屏幕大小 .
- Android屏幕适配大法