Вопрос

I have to implement something that let me run simultaneously many processes in background. The problem is I don't know how many of those from the beginning and all of them have to be processed in the same way but with different parameters. I'm wondering what's the best ways to implement it both as efficiency and as low battery cost. Any help would be really appreciate.

Это было полезно?

Решение

To add to the answers that suggest a Service - depending on your requirements, you need to consider that the Service code will be run on the main application thread, just like code inside an Activity.

Excerpt from the Service page in the Developer Guide:

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

What this means is that its not the same as running a background thread.

If you need true background processing, you should consider running each of your processes in a background thread that is started by the Service.

The Service allows you to run when your app is not in the foreground. The multiple threads allow it to run off the main UI thread.


In terms of managing these multiple threads, consider the use of something like the ThreadPoolExecutor. Full description of every aspect of that is out of scope for this question, but I believe you will learn a lot by reading the Developer Guide link. They provide a lot of detail plus some demo code.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top