从此
文章
📄文章 #️⃣专题 🌐上网 📺 🛒 📱

Android反射获取进程名或用安卓新系统Application.getProcessName()

🕗2024-04-27
/**
* 主进程名和同包进程名均能获取 等同API Level 28的Application.getProcessName()
* Android通过反射获取进程名
*/
public static String getProcessName() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
return Application.getProcessName();
}

// 低于API Level 28则用反射方式获取当前进程名:
String processName = null;
try {
@SuppressLint("PrivateApi") final Method declaredMethod =
Class.forName("android.app.ActivityThread", false, Application.class.getClassLoader())
.getDeclaredMethod("currentProcessName", (Class<?>[]) new Class[0]);
declaredMethod.setAccessible(true);
final Object invoke = declaredMethod.invoke(null, new Object[0]);
if (invoke instanceof String) {
processName = (String) invoke;
}
} catch (Throwable e) {
System.err.println(e);
}
return processName;
}