很多时候一些库、SDK需要在Application onCreate中初始化, 如果App是多进程模式, Application onCreate中初始化会执行多次. 导致初始化代码执行了多次.
思路就是判断当前进程是主进程才执行初始化代码.
if (TextUtils.equals(getCurrentProcessName(this), getPackageName())) {
init();//判断成功后才执行初始化代码
}
getCurrentProcessName()
private String getCurrentProcessName(Context context) {
int pid = android.os.Process.myPid();
ActivityManager mActivityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}