Use of Android Multithread AsyncTask

Keywords: Android

Recently, the frequent use of Handler in projects has made the project particularly bloated. I don't think it's good, so I used another method of asynchronous operation, AsyncTask!

Advantages of using AsyncTask
Clear structure, clear function definition, simple and clear for each background task.

Disadvantages of using AsyncTask
When dealing with single background asynchronously, it appears that there is too much code and too complex structure (I think that a single background directly uses Handler, threading is the kingdom)

introduce
Android's syncTask is lighter than Handler's and is suitable for simple asynchronous processing.
First of all, it is clear that the reason why Android has Handler and SyncTask is to not block the main thread (UI thread), and UI updates can only be completed in the main thread, so asynchronous processing is inevitable.

Android provides AsyncTask to reduce the difficulty of this development. AsyncTask is an encapsulated background task class, as the name implies, an asynchronous task.

AsyncTask is directly inherited from the Object class, located in android.os.AsyncTask. To work with AsyncTask, we need to provide three generic parameters and overload several methods (at least one).
Three Generics of AsyncTask
Params starts the input parameters for task execution, such as the URL of the HTTP request.
Percentage of background task execution for Progress.
Result Background Execution Task Returns the final result, such as String.

Using AsyncTask, you have to rewrite these two methods
doInBackground(Params... ) Background execution, more time-consuming operations can be placed here can not directly operate the UI. PucProgress can be tuned during execution. ) To update the progress of the task.

onPostExecute(Result) is equivalent to the way Handler handles the UI, in which the result obtained in doInBackground can be used to process the UI. This method is executed in the main thread, and the result of task execution is returned as a parameter of this method.

If necessary, you have to rewrite the following three methods, but not necessarily:

OnProgress Update ) You can use progress bars to increase user experience. This method is executed in the main thread to show the progress of task execution.

onPreExecute() Here is the interface when the end user calls Excute. This method is called before the task is executed, and the progress dialog box can be displayed here.
Operation to be done when onCancelled() user calls cancel

The following points should be noted when using the AsyncTask class

Task instances must be created in UI thread s;
The execute method must be called in the UI thread.
Do not manually call onPreExecute(), onPostExecute(Result), doInBackground(Params... ) onProgress Update ) These methods;
This task can only be executed once, otherwise it will be abnormal when it is called many times.

If you don't understand it very well, it's only the top one. See a very simple example.
First is the layout file.

<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_marginTop="70dp"
            android:layout_marginLeft="20dp"
            android:id="@+id/textView"
            android:text="case"
            android:textSize="20dp"
            android:textStyle="bold"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
    </ScrollView>

</android.support.v4.widget.SwipeRefreshLayout>

Then there's the program code.

public class MainActivity extends AppCompatActivity {
    private SwipeRefreshLayout swipeRefreshLayout;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                ProgressBarAsyncTask asyncTask = new ProgressBarAsyncTask(textView);
                asyncTask.execute(1000);
            }
        });
    }

    class ProgressBarAsyncTask extends AsyncTask<Integer, Integer, String> {
        private TextView textView;


        public ProgressBarAsyncTask(TextView textView) {
            super();
            this.textView = textView;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            textView.setText("Start executing asynchronous threads");
        }

        @Override
        protected String doInBackground(Integer... params) {
            Operator netOperator = new Operator();
            int i = 0;
            for (i = 0; i <= 5; i++) {
                netOperator.operator();
                publishProgress(i);
            }
            return i + params[0].intValue() + "";
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            textView.setText("End of asynchronous operation execution" + s);
            swipeRefreshLayout.setRefreshing(false);
        }
    }
}

A Kind of Sleep Tools

public class Operator {
    public void operator(){
        try {
            //Sleep for one second.
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Top effect diagram_

Posted by krio on Sun, 24 Mar 2019 10:27:27 -0700