The fourth chapter of Android advanced application development -- AsyncTask

Posted by astricks on Sat, 04 Apr 2020 00:15:13 +0200

        **The fourth chapter of Android advanced application development -- AsyncTask**

1, What is AsyncTask?

1.AsyncTask is a lightweight (less code) asynchronous class provided by Android.
2. In order to reduce the development difficulty of asynchronous communication, AsyncTask is provided.
3.AsyncTask directly inherits from the object class and is located in the android.os package.
4. With AsyncTask, complex objects such as Looper, MessageQueue and Handler can be ignored, making asynchronous and time-consuming operations more convenient.

2, How to use AsyncTask?

1. Create a new inner class to inherit AsyncTask.
2. Define three generic parameters of AsyncTask.
3. Override the doInBackground abstract method.
4. Override the onPreExecute method.
5. Override the onProgressupdate method.
6. Override the onPostExecute method.
7. Call the execute method where you need to start.

3, Use AsyncTask for countdown (with code)
1. Layout file:

    <TextView
        android:id="@+id/main2_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Count down"
        android:textSize="32sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/main2_edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Input number"/>
    <Button
        android:id="@+id/main2_downbtn"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="start"/>

2.java file:


public class Main2Activity extends AppCompatActivity {

    private TextView textView;
    private EditText editText;
    private Button button;

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


        bindID();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int time = Integer.parseInt(editText.getText().toString());
                new Mytask().execute(time);
            }
        });
    }

    private void bindID()//Bind id {
        textView = findViewById(R.id.main2_text);
        editText = findViewById(R.id.main2_edit);
        button = findViewById(R.id.main2_downbtn);
    }

    class Mytask extends AsyncTask<Integer, Integer, String> {

        @Override
        protected void onPreExecute()//onPreExecute method{
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(Integer... integers) {
            for (int i =integers[0]; i >=0; i--) {
                try {
                    Thread.sleep(1000);//One second apart
                    publishProgress(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "End";
        }

        @Override
        protected void onProgressUpdate(Integer... values)//onProgressUpdate method{
            super.onProgressUpdate(values);
            textView.setText(values[0]+"");
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            textView.setText(s);
        }
    }
}
</LinearLayout>

4, Use AsyncTask to make progress bar (with code)
1. Layout file:

<SeekBar
       android:id="@+id/main_bar1"
       android:layout_width="match_parent"
       android:layout_height="40dp" />
       <SeekBar
       android:id="@+id/main_bar2"
       android:layout_width="match_parent"
       android:layout_height="40dp" />

    <Button
        android:id="@+id/main_btn1"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="1 Start downloading"/>
        <Button
        android:id="@+id/main_btn2"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="1 Start downloading"/>

**2.java Document:**

private SeekBar seekBar1;
    private SeekBar seekBar2;
    private Button button1;
    private Button button2;

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

        bindID();
    }

    private void bindID() {
        seekBar1 = findViewById(R.id.main_bar1);
        seekBar2 = findViewById(R.id.main_bar2);
        button1 = findViewById(R.id.main_btn1);
        button2 = findViewById(R.id.main_btn2);
        button1.setOnClickListener(this);

       seekBar1.setMax(10);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_btn1:
                button1.setEnabled(false);
                button1.setText("Downloading");
                new MyTask().execute();
                break;
            case R.id.main_btn2:
                break;
        }
    }
    class MyTask extends AsyncTask<Integer,Integer,Integer>{

        @Override
        protected Integer doInBackground(Integer... integers) {



            for(int i=0;i<=10;i++){
                try {
                    Thread.sleep(1000);
                    publishProgress(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
             return 1;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            seekBar1.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
button1.setText("Download complete");
button1.setEnabled(true);
        }
    }
}

5, What's the difference between Execute() and executeOnExecutor?

The executeOnExecutor method can Execute multiple tasks at the same time, up to five tasks at the same time. When Execute starts multiple tasks at the same time, it will Execute one by one in order.

6, Prefer to use AsyncTask or Handler, why?

Prefer to use AsyncTask. Because you only need to know three parameters and several methods to use AsyncTask. The code is small and the structure is clear. The Handler needs to know five parameters, which has a large amount of code and confusing logic.

Topics: Android Java less