在代码中引入多进程,需要判断是否是主进程的时候,可以利用SharedPreferences来记录第一次调用Application的onCreate方法时候的processName。这样不用利用包名来判断是否是主进程名,即使在Manifest文件中配置了process也依旧能够判断。
public class MyApplication extends Application {
private static final String TAG = "processStudy";
private static final String pKey = "processName";
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "application onCreate: ");
String currentProcessName = getCurrentProcessName();
if (PrefUtil.getString(getApplicationContext(), pKey)==null){
PrefUtil.putString(getApplicationContext(), pKey, currentProcessName);
}
String mainProcessName = PrefUtil.getString(getApplicationContext(), pKey);
if (currentProcessName.equals(mainProcessName)){
Log.d(TAG, "onCreate: "+currentProcessName+" is main process");
}
}
private String getCurrentProcessName() {
int pid = Process.myPid();
String currentProcessName = "";
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo: runningAppProcesses){
Log.d(TAG, "processName: "+processInfo.processName+" processId:"+processInfo.pid);
if (pid==processInfo.pid){
currentProcessName = processInfo.processName;
}
}
return currentProcessName;
}
}