我正在使用一段代码,它取自 Google 的WorkManager库。在撰写本文时,它位于GreedyScheduler.java
. 已经定义getProcessName()
了这样的方法:
@Nullable
private String getProcessName() {
if (SDK_INT >= 28) {
return Application.getProcessName();
}
// Try using ActivityThread to determine the current process name.
try {
Class<?> activityThread = Class.forName(
"android.app.ActivityThread",
false,
GreedyScheduler.class.getClassLoader());
final Object packageName;
if (SDK_INT >= 18) {
Method currentProcessName = activityThread.getDeclaredMethod("currentProcessName");
currentProcessName.setAccessible(true);
packageName = currentProcessName.invoke(null);
} else {
Method getActivityThread = activityThread.getDeclaredMethod(
"currentActivityThread");
getActivityThread.setAccessible(true);
Method getProcessName = activityThread.getDeclaredMethod("getProcessName");
getProcessName.setAccessible(true);
packageName = getProcessName.invoke(getActivityThread.invoke(null));
}
if (packageName instanceof String) {
return (String) packageName;
}
} catch (Throwable exception) {
Log.d("TAG", "Unable to check ActivityThread for processName", exception);
}
// Fallback to the most expensive way
int pid = Process.myPid();
ActivityManager am =
(ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
if (am != null) {
List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();
if (processes != null && !processes.isEmpty()) {
for (ActivityManager.RunningAppProcessInfo process : processes) {
if (process.pid == pid) {
return process.processName;
}
}
}
}
return null;
}
然后在调用方:
boolean isMainProcess() {
return TextUtils.equals(mContext.getPackageName(), getProcessName());
}