I want to execute an asynctask after finishing the first task. But when printing the status the of the first task it always shows RUNNING.If execute both tasks parallel only smaller task will be executed. I am running both in activity oncreate method.Any idea?
here is my code sample
public class test extends Activity
{
ExecuteTask1 task1;
ExecuteTask2 task2;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
task1 = new ExecuteTask1();
task1.execute(token);
System.out.println(task1.getStatus());
if(task1.getStatus() ==AsyncTask.Status.FINISHED)
{
task2 = new ExecuteTask2();
task2.execute(token);
}
}
}
Use getStatus() to get the status of your AsyncTask . If status is AsyncTask. Status. RUNNING then your task is running.
In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.
Generally you should set a flag in your AsyncTask class or return an appropriate result from your doInBackground() so that, in your onPostExecute() , you can check if you could finish what you want or if your work was cancelled in the middle. Save this answer.
This class was deprecated in API level 30.AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.
In your code right now, you aren't giving task1 time to finish. Start task2 from the onPostExecute
method of task1. (You'll have to modify the code in class ExecuteTask1 for this to work.)
Alternatively, have task1 call back to your activity (or post a message to it or something) in onPostExecute
so your activity can then start task2.
That's because you get status of task1
right after you start it - you need to call second AsyncTask from first one's onPostExecute()
, using handler or some other way.
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