A small part of my application checks if files exist on the user’s device. The list of files is potentially quite long – apparently long enough to cause ANR’s with a few users. A thousand files is by no means impossible.
The code is quite simple:
new File(fileUrl).exists()
I’m currently doing it on the main thread, as I need the operations to be blocking. I could do it using an AsyncTask class and then continue the rest of the work once it’s done, but I’m wondering if that’s a valid cause?
All the work is being done in a background Service, if that changes anything. I’m also potentially going to experience orientation changes, and that might be annoying with AsyncTask. Would a Handler be better?
So, to sum things up: Should I do use an AsyncTask for a potentially long-running operation in a background Service, where orientation changes may occur?
Firstly, a
Serviceisn’t affected by orientation change – it’s only the currently runningActivityclass which is destroyed / recreated.Secondly, an
AsyncTaskisn’t of much advantage in aServiceas it’s designed to be able to interact with the UI. It would give the advantage of doing work on a separate thread but the rest of the methods would basically be redundant.I’d recommend using an
IntentServicewhich manages its own worker thread to do work. See the IntentService documentation