Can I startService from Application#onCreate()?

Cedric Fung picture Cedric Fung · Aug 26, 2011 · Viewed 10.3k times · Source

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.

Answer

Rajiv Makhijani picture Rajiv Makhijani · Aug 26, 2011

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"?