How to check if Async Task is already running

Kevin Bradshaw picture Kevin Bradshaw · Sep 2, 2012 · Viewed 48.9k times · Source

I have an app that needs to do an intensive database operation on start up. The app holds a local copy of the contacts on the phone and synchronizes with the android contact database on startup.

If a user starts the app, an Async Task is started that does the database synch in the background. If the user closes the app, the operation continues running which is fine. However if the user opens the app again, the Async Task is started and an error is produced.

Is there anyway of checking if the Task is already running from a different instance of the app?

Answer

Ovidiu Latcu picture Ovidiu Latcu · Sep 2, 2012

Use getStatus() to get the status of your AsyncTask. If status is AsyncTask.Status.RUNNING then your task is running.

EDIT: you should reconsider your implementation and hold the AsyncTask probably in a Service or IntentService to fetch your data from the web.