Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 460
Cedric Fung Avatar asked Aug 26 '11 00:08

Cedric Fung


People also ask

How do I start a service from another app?

You should be able to start your service like this: Intent i = new Intent(); i. setComponent(new ComponentName("com. xxx.

Can we start a service from a broadcast receiver?

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.

How do I stop an Android application from closing?

In android, by pressing a back button or home button. So put an event key listener for back & home button and terminate the service.

Which method is called when app is killed Android?

When Android decides to kill our app, our activities will call onDestroy method.


2 Answers

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

like image 88
Rajiv Makhijani Avatar answered Oct 11 '22 12:10

Rajiv Makhijani


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.

like image 30
Dan S Avatar answered Oct 11 '22 10:10

Dan S