4

I have an activity which gets called every time a Call is ended. This activity has below AsyncTask.

UploadRecordings uploadRecordings = new UploadRecordings();
uploadRecordings.execute(context);

Now when I get many Calls one after another, everytime new AysncTask is created. But Android limits the number of AsyncTask to 5. So problem is I want to check if a AsyncTask is already running, and if found running, don't create a new AsyncTask. I want to create a new AsyncTask if there is no AsyncTask running.

Any Help be Appreciated.

Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95
Mehul Kanzariya
  • 888
  • 3
  • 27
  • 58
  • 1
    For Simple Solution create boolean value and set after completion of asynctask in onPostexecute(). You can use simple interface class for this. – Mukeshkumar S Apr 24 '17 at 05:41

5 Answers5

9

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

check this way

if(uploadRecordings.getStatus() == AsyncTask.Status.RUNNING){
    // My AsyncTask is currently doing work in doInBackground()
}

For More Detail Read : Android, AsyncTask, check status?

Community
  • 1
  • 1
Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95
6

You can use getStatus ()

Returns the current status of this task.

if(YourAsyncTaskOBJ.getStatus() == AsyncTask.Status.RUNNING)
    {
      // AsyncTask Running  
    }

Read How to check if Async Task is already running

Community
  • 1
  • 1
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

Override onPostExecute() method of AsyncTask, which is executed whenever a call is completed. Set some flags in onPostExecute() and proceed accordingly.

Suhayl SH
  • 1,213
  • 1
  • 11
  • 16
0

Dealing with AsyncTask

Put the AsyncTask in a Fragment.

Using fragments probably is the cleanest way to handle configuration changes. By default, Android destroys and recreates the fragments just like activities, however, fragments have the ability to retain their instances, simply by calling: setRetainInstance(true), in one of its callback methods, for example in the onCreate().

please find full implementation and description to deal with AsyncTask.

Handle Android AsyncTask

Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43
0

If you want to create a single AsyncTask when nothing is already running, you can do something like:

if(uploadRecordings == null || uploadRecordings.getStatus() != AsyncTask.Status.RUNNING){
   uploadRecordings = new UploadRecordings();
   uploadRecordings.execute(context);
}

This assumes that your uploadRecordings is a member variable. e.g.

private UploadRecordings uploadRecordings = null;

Enzokie
  • 7,365
  • 6
  • 33
  • 39