public static String getProcessName_1() {
try {
File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
return processName;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getProcessName_2(Context context) {
// 获取此进程的标识符
int pid = android.os.Process.myPid();
// 获取活动管理器
ActivityManager activityManager = (ActivityManager)
context.getSystemService(Context.ACTIVITY_SERVICE);
// 从应用程序进程列表找到当前进程,是:返回当前进程名
for (ActivityManager.RunningAppProcessInfo appProcess :
activityManager.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
public static String getProcessName_3() {
String processName = null;
try {
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) {
}
return processName;
}
@RequiresApi(api = Build.VERSION_CODES.P)
private String getProcessName_4() {
return Application.getProcessName();
}
对比下四种方式:
1和2的耗时相差不大,1的耗时图如下
1的耗时主要集中在字符串的拼接、FileReader的创建和File文件的读取,这3项耗时占比80%
方法2的耗时集中在跨进程通信,耗时占比90%
方法4是当之无愧的冠军,但是对系统版本有要求。
融合方法3和方法4:
public String processName(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
return getProcessName_4();
}else{
return getProcessName_3();
}
}