Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple threads in Android activity/service

I have an android app, where in a list view for each element in list, I load an image from web in a separate thread. So if there are 8 items displayed in list view, activity will try to fire 8 different threads, one for each list item to load an image. As you scroll down the list, the number of threads may increase if the previous threads haven't finished executing.

I am curious to know how many simultaneous threads can a single android app execute in parallel? Is there a limit? I wouldn't expect these threads to cause a ANR over slow internet connection as they are independent? But it seems that ANR does happen and may be it's because app/device run low on resources, so spawning a new activity in UI takes more than 5 seconds which results in an ANR?

Any clues to how I can make responsiveness better on a slow internet connection will be appreciated.

like image 235
Priyank Avatar asked Dec 21 '22 22:12

Priyank


1 Answers

Later on I found out that my app was hung and slow not because there were too many threads spawned by it. But it was instead because of the fact that I was using Service and not IntentService. And my network IO was happening on main thread in Service. Which means a blocking IO will choke the main thread and phone/app will tend to die and pop up an ANR.

I later on changed my design to run network IO operations in spawned threads in my Services, that put the life back in the app. Everything was smoother as expected.

So whenever your services are resulting in ANR, ensure that if you are not using IntentService(they fire jobs in a separate threads), then you fire blocking operations in new threads.

Hope that helps someone.

like image 86
Priyank Avatar answered Dec 27 '22 20:12

Priyank