要獲取當前進程名,可以使用Android的ActivityManager類的getRunningAppProcesses()方法。以下是一個示例代碼:
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
int pid = android.os.Process.myPid();
String processName = "";
for (ActivityManager.RunningAppProcessInfo process : processes) {
if (process.pid == pid) {
processName = process.processName;
break;
}
}
Log.d("Process Name", processName);
這段代碼會獲取當前進程的PID,然后遍歷所有正在運行的進程,找到與PID匹配的進程,并獲取其進程名。最后,通過Log.d()方法打印出進程名。
請注意,在AndroidManifest.xml文件中,需要添加GET_TASKS權限:
<uses-permission android:name="android.permission.GET_TASKS" />