Darpan
Darpan

Reputation: 5795

Starting service multiple times will nest calls made in onStartCommand()?

I am calling startService() multiple times in my class.

there is a function in my service's onStartCommand(), like this -

    Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(StaticValues.TAG, "service started.");
        processItem();
        return 0;
    }

My question is, if I start service again, onStartComamnd() will be called again. So will this call wait till my previous call is over or it will execute both calls to processItem() parallelly?

Edit : Answer I found from links in comments

startService() is asynchronous. So while you are looping the calls, the service itself hasn't gotten any resources and didn't start yet.

The Service will only run in one instance. However, everytime you start the service, the onStartCommand() method is called.

Check : What happens if a Service is started multiple times?

Upvotes: 2

Views: 1485

Answers (1)

Junaid
Junaid

Reputation: 7860

A Service can only be started once, if you want to and love to complicate things use a boolean flag

Using startService() overrides the default service lifetime that is managed by bindService(Intent, ServiceConnection, int): it requires the service to remain running until stopService(Intent) is called, regardless of whether any clients are connected to it. Note that calls to startService() are not nesting: no matter how many times you call startService(), a single call to stopService(Intent) will stop it.

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.

Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called;

Link to the Docs

Life Cycle of a Service

Upvotes: 1

Related Questions