AsyncTask Learning with Android Multithreading

Catalog

1. Definition

Introduction of 1.13 Generic Parameters

1.2 Four steps of task execution

2. Demo example

1. Definition

Official explanation: AsyncTask can use UI threads correctly and conveniently. This class allows you to perform background operations and publish results on UI threads without manipulating Thread and Handler. AsyncTasks should be used for short operations (up to a few seconds). Asynchronous tasks run calculations on background threads, and the results are published on UI threads.

Introduction of 1.13 Generic Parameters

java.lang.Object
   ↳	android.os.AsyncTask<Params, Progress, Result>

1. Params (input parameter type): The parameters passed to Task when execute() executes.

2. Progress: The type of progress unit that asynchronous tasks perform in the background.

3. Result (Execution Result Type): The type of result returned by the background after performing an asynchronous task is calculated.

If not, the Void type, such as:

private class MyTask extends AsyncTask<Void, Void, Void> { ... }

1.2 Four steps of task execution

1. onPreExecute(): Work in the UI thread and execute before the doInBackground() task is computed

2. doInBackground(Params...): Work in the thread pool, so no UI operations can be performed immediately after onPreExecute() is executed. The params parameters are passed in by calling the execute() method in the main thread. When the calculation is completed, the results are returned to the onPostExecute(Result) method. You can also pass the execution progress to the onProgressUpdate(Progress) method by calling the publishProgress method.

3. onProgressUpdate(Progress...): Working in the UI thread, it executes after the publishProgress() method is executed in doInBackground(). This method is used to display the calculation execution progress through the UI when the background calculation is still executed (that is, doInBackgound() is still executed), so that users can know the progress of the background task execution. Degree.

4. onPostExecute(Result): Work in the UI thread and execute after the doInBackground() execution passes the result in.

 

2. Demo example

Detailed code:

public class AsyncTaskActivity extends AppCompatActivity implements View.OnClickListener {
    private ProgressBar progressBar;
    private TextView displayTv;
    private Button startBtn, stopBtn;
    private MyAsyncTask myAsyncTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task);

        progressBar = findViewById(R.id.progress_bar);
        displayTv = findViewById(R.id.display_tv);
        startBtn = findViewById(R.id.start_btn);
        stopBtn = findViewById(R.id.stop_btn);
        myAsyncTask = new MyAsyncTask();

        startBtn.setOnClickListener(this);
        stopBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start_btn:
                myAsyncTask.execute("Jere test");
                //AsyncTask can only be executed once, and if you call execute() again to execute it during the execution of AsyncTask, you will jump IllegalStateException exception.
                //java.lang.IllegalStateException: Cannot execute task: the task is already running.
                startBtn.setEnabled(false);
                break;
            case R.id.stop_btn:
                //Interrupt thread execution
                myAsyncTask.cancel(true);
                break;
            default:
                break;
        }
    }

    /**
     * Create MyAsyncTask class, inherit AsyncTask class - > AsyncTask < Params, Progress, Result >
     * 3 Generic parameters specify types:
     * Params(Input parameters): String type
     * Progress(Progress of execution): Integer type
     * Result(Execution results): String type
     */
    private class MyAsyncTask extends AsyncTask<String, Integer, String> {

        /**
         * Perform the onPreExecute() operation before the background task starts to calculate execution
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            displayTv.setText("onPreExecute: start! ");
            Toast.makeText(AsyncTaskActivity.this, "onPreExecute", Toast.LENGTH_SHORT).show();
        }

        /**
         * Receive the input parameters, perform the calculation work (time-consuming operation) in the background task, finish the calculation and return the calculation results.
         * @param strings Params Enter parameters to execute() incoming parameters in the main thread
         * @return Returns the execution result to onPostExecute()
         */
        @Override
        protected String doInBackground(String... strings) {
            for (int i = 1; i <= 10; i++) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //By calling the publishProgress() method, the execution progress is passed to onProgressUpdate()
                publishProgress(i);
            }

            String result;
            result = Arrays.toString(strings) + " return from doInBackground";
            return result;
        }

        /**
         * The receiving background calculates the execution progress and realizes the execution progress through ProgressBar in the UI thread.
         * @param values :  Execution progress, passed in through publishProgress()
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //Get an integer array, but each time there's only one element in it, all of which get the current execution progress through values[0].
            progressBar.setProgress(values[0]);
            displayTv.setText("onProgressUpdate: value = " + values[0]);
        }

        /**
         * Receive the result returned by the end of background task calculation and display it on the UI thread
         * @param s : The execution result returned by the end of the background calculation is returned by doInBackground().
         */
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            displayTv.setText("onPostExecute: " + s);
            Toast.makeText(AsyncTaskActivity.this, "onPostExecute", Toast.LENGTH_SHORT).show();
        }

        /**
         * Call cancel() method in the main thread, execute onCancelled(), and cancel background tasks
         *
         * When a task is computed, it cannot be cancelled, or it cannot be cancelled again after it has been cancelled.
         */
        @Override
        protected void onCancelled() {
            super.onCancelled();
            displayTv.setText("onCancelled");
            progressBar.setProgress(0);
            Toast.makeText(AsyncTaskActivity.this, "onCancelled", Toast.LENGTH_SHORT).show();
        }

    }

}

The effects of additional interruptions are as follows: (1)

 

See the specific code (viii) source code

Tags: Java Android

Posted on Fri, 06 Sep 2019 23:50:54 -0700 by zahadum