I am starting an android service using,
startService(getApplicationContext(), MyService.class);
I have correctly defined my service in AndroidManifest. Now, I am calling above code from Application create.
Case 1: Calling above code from Application onCreate()
Case 2: Calling above code from Activity in application
Is this intended behavior?
My Android Manifest Code as requested:
<service
android:exported="false"
android:enabled="true"
android:name=".MyService"
android:process=".MyService">
</service>
The Activity lifecycle consists of 7 methods: onCreate() : When a user first opens an activity than the first method that gets called is called as onCreate. It acts the same as a constructor of a class, then when an activity is instantiated then onCreate gets called.
onCreate() - called before the first components of the application starts. onLowMemory() - called when the Android system requests that the application cleans up memory.
A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. A service is bound when an application component binds to it by calling bindService().
Fundamentals of Android Services requests to start a service using startService(). Once the service is started, it can be stopped explicitly using stopService() or stopSelf() methods.
Since you specified the android:process
attribute in your <service>
element, and its value is not the same as your application package name, that service is actually running in a separate process from the default process for your application. (I don't know if it was intentional, but you also seem to have a typo in the process name.)
If you did not intend to run the service in a separate process (which is rare, and something you should only do if you have a good reason and understand the implications), you should just omit the android:process
attribute in your <service>
element -- this would cause it to run in the same process as the rest of your app.
A little-known and seemingly undocumented behavior of Android is that each process of an application has is own Application
instance. This explains why starting your service created an additional Application
instance.
Also, not only do the 2 processes have their own Application instances, they actually have their own Application classes, since they do not even share the same class loaders. Therefore, even their static variables can have different values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With