I want to start a service when my Application is initialized from whatever component.
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
startService(new Intent(getApplicationContext(), MyService.class));
}
}
Is the Service available in the onCreate()
state? Will the super.onCreate()
initialize all components of an Application registered in the AndroidManifest.xml ?
I can run this code in my galaxy s, but I can't make sure it will be run in all devices and platforms, I can't find any documentation about the initialization of an Android APP.
You should be able to start your service like this: Intent i = new Intent(); i. setComponent(new ComponentName("com. xxx.
As an Android developer, you'll often run into the scenario where you need to perform tasks and display notifications for your app in the background. To retain battery power on our users device we are going to run background tasks using a broadcast receiver.
In android, by pressing a back button or home button. So put an event key listener for back & home button and terminate the service.
When Android decides to kill our app, our activities will call onDestroy method.
Yes, you can start a service in onCreate()
the way you are doing so. There is no guarantee that the service will successfully start though - as long as the service exists on the device and is able to run, it will. super.onCreate()
does not do any preparation that is required to start a service from within your application. What do you mean by "Is the service available in the onCreate() state"?
In short Yes, the Context.startService() but the doc also says that if it returns null the service is not available.
If the service is being started or is already running, the ComponentName of the actual service that was started is returned; else if the service does not exist null is returned
This API isn't meant to vary between devices so you can be confident in what you're experiencing on the emulator and devices you have. The on caveat is to remember that Services that require "lots" of resources may act differently, ie cpu time or memory, etc.
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