18

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Cedric Fung
  • 477
  • 1
  • 4
  • 12
  • In this case How we can get the Service object back in Application... and from where onBind is called ? – Amit Feb 05 '13 at 13:28

2 Answers2

10

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

Rajiv Makhijani
  • 3,631
  • 32
  • 31
  • The service is from my app, so it exists surely. By "Is the service available in the onCreate() state", I mean whether the Service is ready to be started in Application#onCreate() (not Activity#onCreate()). – Cedric Fung Aug 26 '11 at 01:16
  • 1
    The Service will be ready to start. onCreate does not need to run before the Service will be available to start (i.e. onCreate does not do class-loading necessary to load a Service from your application). – Rajiv Makhijani Aug 26 '11 at 01:18
1

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.

Dan S
  • 9,139
  • 3
  • 37
  • 48