using android:process=“:remote” recreates android

2019-02-22 15:35发布

问题:

I'm using AIDL service in my app. I also want to run it another process, so I use android:process=":remote" in service declaration in the manifest.

My problem is that when the :remote process starts it apparently recreates Application object.

I really do not with that as I override application object and call lots of client stuff in the onCreate() method. Yet I want the service code to reside in the same apk with the client.

Can I achieve that? Is Application object always recreated when new process starts?

Appreciate your help. Thanks!

回答1:

I also want to run it another process

Why? What value does that add to the user, to offset the additional RAM, CPU, and battery cost? Very few apps need more than one process.

My problem is that when the ':remote' process starts it apparently recreates Application object

Of course. Each process gets its own.

I really do not with that as I override application object and call lots of client stuff in the 'onCreate()' method

Then get rid of android:process=":remote". Your users will thank you.

Yet I want the service code to reside in the same apk with the client.

What service?

Is Application object always recreated when new process starts?

Yes.



回答2:

As already mentioned by CommonsWare, each of the processes gets its own Application object.

In your Application.onCreate() method you can check whether the method is being called from within the main process or from within the remote process and initialize different stuff accordingly.

@Override
public void onCreate()
{
    super.onCreate();

    if(isRemoteProcess(this))
    {
        // initialize remote process stuff here
    }
    else
    {
        // initialize main process stuff here
    }
}

private boolean isRemoteProcess(Context context)
{
    Context applicationContext = context.getApplicationContext();
    long myPid = (long) Process.myPid();
    List<RunningAppProcessInfo> runningAppProcesses = ((ActivityManager) applicationContext.getSystemService("activity")).getRunningAppProcesses();
    if (runningAppProcesses != null && runningAppProcesses.size() != 0)
    {
        for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses)
        {
            if (((long) runningAppProcessInfo.pid) == myPid && "YOUR_PACKAGE_NAME:remote".equals(runningAppProcessInfo.processName))
            {
                return true;
            }
        }
    }
    return false;
}