Android 獲取進程名稱
本篇文章主要獲取下當前應用的進程名稱,具體代碼如下:
public static String getProcessNameDevice(final Context context) {int myPid = Process.myPid();if (context == null || myPid <= 0) {return "";}ActivityManager.RunningAppProcessInfo myProcess = null;// 獲取ActivityManagerActivityManager 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();}}}
}
需要注意:
- 自Android 5.1版本開始,Google限制了對getRunningAppProcesses()方法的訪問權限,只允許獲取當前應用的進程信息,而不允許獲取其他應用或系統進程的信息.