Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynctask status always showing running

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);
            }

     }
}
like image 309
Reji Avatar asked Dec 01 '11 06:12

Reji


People also ask

How do I know if AsyncTask is running?

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

What is the problem with AsyncTask in Android?

In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.

How do I stop AsyncTask when activity is destroyed?

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.

Why was AsyncTask deprecated?

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.


2 Answers

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.

like image 50
Ted Hopp Avatar answered Sep 22 '22 13:09

Ted Hopp


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.

like image 30
Vladimir Avatar answered Sep 22 '22 13:09

Vladimir