简体   繁体   中英

Android Application onCreate Called Twice AppWidget

I have am AppWidget that uses a RemoteService. I'm assuming this causes my Application onCreate to be called even if my app is already running because it's bring started from another process.

The issue is, I initialize a few singletons in onCreate, and they throw IllegalStateExceptions if you try to initialize them again. I can catch those, but then the singletons will have the other Application's Context. What am I supposed to do here?

I am not sure if I understand your question. Since you have two process now, each process will hold its own class instances, including the singletons. But in that case you will not be able to initialize a singleton twice, and the IllegalStateExceptions should not be thrown.

The only way (within my knowledge) you can initialize a singleton twice is that you are trying to start a subprocess twice in Application.onCreate() . If so, to solve the problem is to prevent the process from being started twice.

Since the process names are predetermined, we can use them to identify on which process current code is running. The following method can be used to determine if we are running under application main process:

/**
 * check if current process is the application's main process
 */
public boolean isMainProcess(Context context) {
    String currentProcessName = null;
    int currentPid = android.os.Process.myPid();
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
    if (runningApps != null) {
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == currentPid) {
                currentProcessName = procInfo.processName;
            }
        }
    }
    return context.getApplicationInfo().packageName.equals(currentProcessName);
}

The above code assumes that the process name is not explicitly given in AndroidManifest.xml. That is to say, the process name is the package name.

I used to use this code to check if I should start a subprocess on Application.onCreate() method: only start subprocess when isMainProcess() returns true. Works good for me.

Again, not sure if I fully understand your problem. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM