Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Async Task is already running

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?

like image 271
Kevin Bradshaw Avatar asked Sep 02 '12 14:09

Kevin Bradshaw


People also ask

How do I know if async task is running?

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

Is Async task runs on main thread?

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

How do I stop async tasks?

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

How does async task work internally?

The Async task by default runs the tasks in serial fashion, one after the other. Once the task is not complete, the other tasks are waiting in the Queue to be picked up. We can override this serial runner by passing in our Executor, which can run multiple tasks in Parallel.


1 Answers

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.

like image 98
Ovidiu Latcu Avatar answered Oct 10 '22 05:10

Ovidiu Latcu