Running a service in Android calls apps onCreate

I am starting android service using

startService(getApplicationContext(), MyService.class);

      

I have defined my service correctly in AndroidManifest. Now I am calling the code above from create application.

Case 1: Calling above the code from the application onCreate ()

  • I see that Application.onCreate () is being called two times. One is the desired application and the other is when the startService function starts.

Case 2: Calling Code from an Activity in an Application

  • Same behavior as case 1.

Is this the intended behavior?

My android manifest code as requested:

    <service
            android:exported="false"
            android:enabled="true"
            android:name=".MyService"
            android:process=".MyService">
    </service>

      

+3


source to share


1 answer


Because you specified an attribute android:process

on an element <service>

and its value does not match the name of your application package, this service is actually run by a separate process from the default process for your application. (I don't know if this was intentional, but you also have a typo in the process name.)

If you didn't intend to start the service in a separate process (which is rare, and you only need to do something if you have a good reason and understand the implications), you should simply omit the attribute android:process

in yours <service>

- this will cause it to work in the same process as the rest of the application.



A little known and seemingly undocumented behavior of Android is that each process in an application has its own Application

instance
. This explains why an additional instance was created when your service started Application

.

Also, not only do the two processes have their own application instances, they actually have their own application classes since they don't even use the same classloaders. Therefore, even their static variables can have different values.

+3


source







All Articles