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?
Use getStatus() to get the status of your AsyncTask . If status is AsyncTask. Status. RUNNING then your task is running.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With