android获取processId
2018-10-20 本文已影响0人
WLHere
- 获取当前进程id
android.os.Process.myPid()
- 根据包名获取进程id
public static int getPidByProcessName(Context context, String packageName) {
if (StringUtils.isBlank(packageName)) {
return -1;
}
ActivityManager mActivityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
// 通过调用ActivityManager的getRunningAppProcesses()方法获得系统里所有正在运行的进程
List<ActivityManager.RunningAppProcessInfo> appProcessList = mActivityManager
.getRunningAppProcesses();
if (appProcessList != null) {
for (ActivityManager.RunningAppProcessInfo appProcess : appProcessList) {
if (packageName.equals(appProcess.processName)) {
return appProcess.pid;
}
}
}
return -1;
}