Reputation: 2079
I want to run multiple threads in service. Like in google doc example:
http://developer.android.com/guide/components/services.html
However, because you handle each call to onStartCommand() yourself, you can perform multiple requests simultaneously. That's not what this example does, but if that's what you want, then you can create a new thread for each request and run them right away (instead of waiting for the previous request to finish).
How I can perform multiple request simultaneously?
For example I want 10 threads that starts depend on Message.what.
How and where to create this 10 thread? In OnCreate
in service?
But OnCreate
exec only once when I create service. But if I want to add threads to service dynamically
and generate message
depends on intent extras
? For example:
Intent intent1 = new Intent(this, SimpleService.class);
intent1.putExtra("what", 1);
Intent intent2 = new Intent(this, SimpleService.class);
intent2.putExtra("what", 2);
...
startService(intent1);
startService(intent2);
...
And I should to create 10 handlers and 10 looper for each threads?
Thank You!
Upvotes: 0
Views: 2836
Reputation: 1006539
How I can perform multiple request simultaneously?
Use a ThreadPoolExecutor
, configured for a reasonable number of threads (e.g., 2 times the number of cores, plus 1).
How and where to create this 10 thread? In OnCreate in service?
You can set up the ThreadPoolExecutor
in onCreate()
, or possibly just in a field initializer.
But OnCreate exec only once when I create service.
Which is why you use ThreadPoolExecutor
and configure it for an appropriate number of threads.
But if I want to add threads to service dynamically and generate message depends on intent extras?
Just call submit()
in onStartCommand()
to add a piece of work to the ThreadPoolExecutor
. If there is an available thread, the work will run right away. If not, you supply a work queue to the ThreadPoolExecutor
, and your submitted work will await a free thread.
Upvotes: 1