A
A
Andrey Ocheretyany2016-09-25 23:07:56
Android
Andrey Ocheretyany, 2016-09-25 23:07:56

How to run two AsyncTasks at the same time so that they run at the same time?

There is a test program like this:

package codeasylum.ua.testasynctask;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    TextView tv1,tv2;
    int i,k;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = (TextView) findViewById(R.id.task1);
        tv2 = (TextView) findViewById(R.id.task2);
        i =0;
        k = 0;
    }


    public void Start(View view) {
        new Task1().execute();
        new Task2().execute();
    }

    class Task1 extends AsyncTask<Void,Integer,Void>{

        @Override
        protected Void doInBackground(Void... voids) {
            int s = 0;
            while (s < 20){
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                s++;
                i++;
                publishProgress(i);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values[0]);
            tv1.setText(values[0]+"");
        }
    }
    class Task2 extends AsyncTask<Void,Integer,Void>{

        @Override
        protected Void doInBackground(Void... voids) {
                int s = 0;
                while (s < 20){
                    s++;
                    k+=2;
                    publishProgress(k);
                }

            return null;
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values[0]);
            tv2.setText(values[0]+"");
        }
    }
}

In it, I'm trying to make two AsyncTasks work at the same time. Those. I want the numbers in the TextView to update at the same time. How to achieve this with AsyncTask? Is it even possible? This could only be done through native Java threads, when I created a separate thread for each task.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Ivanov, 2016-09-26
@eastywest

Perhaps AsyncTaskCompat is what you need.

A
aol-nnov, 2016-09-26
@aol-nnov

if you call a spade a spade, then the answer will be found by itself.
translate from Russian into Russian:
How to run two AsyncTask so that they work synchronously.
open your favorite search engine, clack-clack, iiiii... oops !

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question