在做接口优化的时候发现APP 的Application 的onCreate方法被执行了好几次,导致在onCreate里面做了一些初始化的操作被重复执行了多次,打断点无果,但抓包却真的存在,这令我十分尴尬。。。事后才发现有一些第三方组件,它们是单独开了一个进程
解决办法根据进程名进行初始化过滤,Application 的onCreate 里只初始化一次。
解决方法一:
判断当前进程是主进程才执行初始化代码.
Android避免多进程Application onCreate中初始化代码执行多次
if (TextUtils.equals(getCurrentProcessName(this), getPackageName())) {
init();//判断成功后才执行初始化代码
}
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;
}
解决方法二:
内容摘自:Android多进程时Application初始化问题,大坑
public class MyApplication extends Application {
private final static String PROCESS_NAME = "com.test";
private static MyApplication myApplication = null;
public static MyApplication getApplication() {
return myApplication;
}
/**
* 判断是不是UI主进程,因为有些东西只能在UI主进程初始化
*/
public static boolean isAppMainProcess() {
try {
int pid = android.os.Process.myPid();
String process = getAppNameByPID(MyApplication.getApplication(), pid);
if (TextUtils.isEmpty(process)) {
return true;
} else if (PROCESS_NAME.equalsIgnoreCase(process)) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return true;
}
}
/**
* 根据Pid得到进程名
*/
public static String getAppNameByPID(Context context, int pid) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (android.app.ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
if (processInfo.pid == pid) {
return processInfo.processName;
}
}
return "";
}
@Override
public void onCreate() {
super.onCreate();
myApplication = this;
if (isAppMainProcess()) {
//do something for init
}
}
}