In the last article, I learned how to implement asynchronous Thread and Runnable.
Android asynchronous learning (1): Thread and Runnable
Android asynchronous learning (2): Handler and AsyncTask
Android asynchronous learning (3): RxAndroid
Learn Handler and AsyncTask this time. Let me explain Handler and AsyncTask first.
AsyncTask
AsyncTask is a lightweight asynchronous tool provided by Android.
- Advantages: easy to use, providing an interface for the main steps of the process
- Disadvantages: multiple asynchronous operations at the same time will be complicated
Handler
Handler usually receives messages from the worker thread by overloading the handlerMessage method, and internally performs UI operations on the main thread. Send messages through sendMessage.
Let’s take the download service as an example to illustrate AsyncTask and Handler respectively
AsyncTask
- The layout file
defines a button and progress bar, responsible for start and progress
<Button
android:id="@+id/btn_start"
android:layout_width="160dp"
android:layout_height="60dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_dashboard"
app:layout_constraintEnd_toEndOf="parent"
android:text="Start" />
<ProgressBar
android:id="@+id/pb_down"
android:layout_width="match_parent"
android:layout_height="24dp"
android:layout_marginTop="10dp"
android:layout_marginHorizontal="20dp"
android:max="100"
android:progressDrawable="@drawable/progressbar_bg"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
app:layout_constraintTop_toBottomOf="@+id/btn_start"/>
- DownAsyncTask
public class DownAsyncTask extends AsyncTask<Integer, Integer, String> {
private ProgressBar progressBar;
private Context context;
public DownAsyncTask(Context context, ProgressBar progressBar) {
super();
this.context = context;
this.progressBar = progressBar;
}
// 该方法在后台执行下载的操作
@Override
protected String doInBackground(Integer... integers) {
int i = 0;
for (; i < 101; i++) {
// 通过该方法可以触发onProgressUpdate,从而更新UI
publishProgress(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 返回值是onPostExecute的参数,可以在onPostExecute中显示进度
return String.valueOf(i);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "开始下载", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// 更新UI
progressBar.setProgress(values[0]);
}
}
- Activity/Fragment is
finally used, just execute the execute method in the defined Button's Click listener.
DownAsyncTask downAsyncTask = new DownAsyncTask(this, mProgressBar);
downAsyncTask.execute();
- Handler
is still the above layout file. Handler can be implemented in two ways
- Mode One Post (Runnable)
- First create a worker thread to implement the Runnable interface, and perform time-consuming operations in run.
- Then use the post method of the handler to update the UI in the run method that implements the Runnable interface.
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
new Thread(new Runnable() {
@Override
public void run() {
// TODO下载操作
int i = 0;
for (; i < 101; i++) {
final int finalI = i;
handler.post(new Runnable() {
@Override
public void run() {
// TODO 更新UI
mProgressBar.setProgress(finalI);
}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
break;
-
Method two Message
- Create a worker thread to inherit Thread, rewrite the run method to perform time-consuming operations, and send Message in the worker thread through the handler.sendMessage method.
- Create a Handler, rewrite the handlerMessage method, receive the Message sent by the worker thread here, and update the UI based on the business execution.
class DownThread extends Thread {
@Override
public void run() {
super.run();
int i = 0;
for (; i < 101; i++) {
handler.sendEmptyMessage(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
new DownThread().start();
handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
// 这里使用msg.what作为进度更新UI
mProgressBar.setProgress(msg.what);
}
};
break;
The above is the basic usage of AsyncTask and Handler. The next article learns the use of RxAndroid.