开发者

Can I startService from Application#onCreate()?

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜