安卓中實作異步任務(2)——使用AsyncTask實作
問題背景
實作demo
(1)實作我們的AsyncTask子類
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MyAsyncTask extends AsyncTask<Integer,Integer,Integer> {
private final String TAG = "AsyncTask";
private TextView textView;
private ProgressBar progressBar;
private Context context;
public MyAsyncTask(TextView textView, ProgressBar progressBar, Context context) {
this.textView = textView;
this.progressBar = progressBar;
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(TAG,"onPreExecute(): " + Thread.currentThread().getName());
}
@Override
protected Integer doInBackground(Integer... ints) {
Integer count = ints[0];
while (count < 10 && !isCancelled()){
// isCancelled()表示判斷目前任務是否被取消,防止在取消異步任務的時候循環不能及時停下
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
Log.d(TAG,"doInBackground(): "+ Thread.currentThread().getName() +" "+count);
publishProgress(count);
}
return count;
}
@Override
protected void onPostExecute(Integer i) {
Log.d(TAG,"onPostExecute(): "+ Thread.currentThread().getName());
textView.setText(i + "");
}
@Override
protected void onProgressUpdate(Integer... values) {
Log.d(TAG,"onProgressUpdate(): " + Thread.currentThread().getName());
textView.setText(values[0]+"");
progressBar.setProgress(values[0]);
}
@Override
protected void onCancelled() {
Log.d(TAG,"nCancelled(): "+Thread.currentThread().getName());
super.onCancelled();
Toast.makeText(context,"任務取消成功", Toast.LENGTH_LONG).show();
}
}
(2)建立我們的activity,對應layout布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".thread.AsyncTaskActivity">
<TextView
android:id="@+id/textView"
android:hint="0"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ProgressBar
style="@android:style/Widget.ProgressBar.Horizontal"
android:id="@+id/progressBar"
android:progress="0"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="啟動任務"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:onClick="doTaskClick" />
<Button
android:text="取消任務"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:onClick="cancelTaskClick" />
</RelativeLayout>
</LinearLayout>
(3)對應我們activity的代碼如下:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class AsyncTaskActivity extends AppCompatActivity {
private TextView textView;
private ProgressBar progressBar;
private MyAsyncTask myAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
textView= findViewById(R.id.textView);
progressBar= findViewById(R.id.progressBar);
}
public void doTaskClick(View view){
myAsyncTask = new MyAsyncTask(textView, progressBar,this);
// 執行異步任務,傳入初始參數
myAsyncTask.execute(1);
}
public void cancelTaskClick(View view){
// 取消異步任務
myAsyncTask.cancel(true);
}
}
執行結果如下:
關鍵代碼分析