出現的問題:
當項目中配置了 android:process=":remote" 這個屬性之後,會新增一個私有進程(包名+":remote"),這個進程裏的Application也會走生命週期,然後onCreate裏面一些初始化功能就會重複執行。
處理:在Application的onCreate()方法裏面,先判斷進程名是否是主進程(主進程名:包名),如果是主進程才執行後面的方法,如果不是主進程(比如remote 私有進程)就直接return。
代碼:
自定義的Application:
@Override
public void onCreate() {
//**********多進程執行處理(onCreate方法僅在主進程執行一次)
String processName = getProcessName(this, android.os.Process.myPid());
if(!getPackageName().equals(processName)){//非主進程不執行onCreate裏面操作
return;
}
Log.d(TAG, "MyApplication-onCreate");
super.onCreate();
//下面是業務初始化內容。。。
//do something...
}
//獲取當前進程名
public static String getProcessName(Context cxt, int pid) {
ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
if (runningApps == null) {
return null;
}
for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
if (procInfo.pid == pid) {
return procInfo.processName;
}
}
return null;
}