Application is initialized multi-times when there were multiple processes in Android.

Android的Application类,在应用冷启动的时候由系统实例化并初始化。因为只有冷启动的时候才实例化,所以大多应用都会把应用的初始化工作放到Application的onCreate()方法中

The Application class is only created and initialized once. Since that, most of Apps put the initialization stuff into the method onCreate() of Application.

但是在应用具有多个进程的时候,Application会在每个进程中都会被初始化一次(共享同一个实例),如果不加处理,会导致应用的逻辑混乱。一般的第三方服务都会指导开发者将初始化放到onCreate()方法中,同时不会出问题,是因为使用了单例模式,所以它们的初始化仅会调用一次。

But if there are not only one process, the Application class would be initialized once in every single process (NOT created, it was one instance shared by different processes). This will cause business logic disordered without proper dispose. However most of 3rd-party service let their developers put their initialization in onCreate() of custom Application class and this will be OK, because their library use Singleton pattern and the initialization will be only called once.

对于App本身的逻辑,需要在应用启动中执行的,比如检查更新等操作,需要在onCreate()方法中执行的话,就需要做额外的处理——通过进程名称判断,仅当当前进程为默认进程时,才执行初始化代码

For logic of App itself, some operation like checking update version need be executed in onCreate(), some extra-operation should be put in there. That is deal with the initialization stuff only if the code was running in the default process.

示例:

Exp.

onCreate()方法:

method onCreate():

@Override
public void onCreate() {
super.onCreate();
String processName = OsUtils.getProcessName(this, android.os.Process.myPid());
if (processName != null) {
boolean defaultProcess = processName.equals(Constants.PACKAGE_NAME);
if (defaultProcess) {
singleInit();
}
}
}

用到的OsUtils类:

OsUtils class:

public class OsUtils {
public static String getProcessName(Context context, int pid) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
if (runningApps == null) {
return null;
}
for (RunningAppProcessInfo procInfo : runningApps) {
if (procInfo.pid == pid) {
return procInfo.processName;
}
}
return null;
}
}

通过这样的方式,就可以避免Application的onCreate方法多次调用了。

By do it this way, multi-executing will be avoided.

 

参考:http://www.cnblogs.com/0616–ataozhijia/p/4203433.html