Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Android) How to run multiple instances of a service

Tags:

android

anyone knows how i can make multiple instances of same service class work seperately, am working on a taxi meter app where i have a "Counter" service which will calculate for me the distance and add locations to database for each client, in my mainactivity i made three instance of the same service and started everyone seperately but it doesn't seem to work as expected(only i made a toast in every service start action but it seem to appear for just one client). i know i have read in several treads that it's no possible to make multiple instance of services work at the same time but this is the only way i could do to make a taxi meter that supports multi clients at the same thing.

like image 484
Karim Benfaida Avatar asked Dec 21 '25 11:12

Karim Benfaida


1 Answers

As rightly pointed out, we cannot have multiple instances of service. A service can only have one instance. Each subsequent call to startService, the method onStartCommand is called again.

But,suppose the onStartCommand instantiates a Timer object to repeat a task every 30 secs. Each subsequent call to startService, a new instance of object Timer is created...!

Now concider following use case:

  1. timer is set up to log "Hello World" after every 30 sec

  2. 1st startService command is issued at 16:00:00

  3. for next 2 mins, you should see 5 "Hello World" printed at

-16:00:00

-16:00:30

-16:01:00

-16:01:30

-16:02:00

  1. Now 2nd startService command is issued at 16:02:10, for next 2 mins, you should see "Hello World" printed as follows:

-16:02:10 (2nd call)

-16:02:30 (1st call)

-16:02:40 (2nd call)

-16:03:00 (1st call)

-16:03:10 (...)

-16:03:30

-16:03:40

-16:04:00

So after 2nd call, two instances of the Timer class exist. But only one Service instance.

like image 60
Parth Kapoor Avatar answered Dec 23 '25 00:12

Parth Kapoor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!