使用AsyncTask实现下载进度条效果
public class AsyncTaskActivity extends Activity implements View.OnClickListener {
private Button mBtnStart;
private Button mBtnCancel;
private TextView mTVShow;
private ProgressBar mProgress;
private MyAsyncTask myAsyncTask;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_asynctask);
initView();
}
private void initView() {
mBtnStart = findViewById(R.id.btnStart);
mBtnCancel = findViewById(R.id.btnCancel);
mTVShow = findViewById(R.id.textShow);
mProgress = findViewById(R.id.progress);
myAsyncTask = new MyAsyncTask();
mBtnStart.setOnClickListener(this);
mBtnCancel.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
myAsyncTask.execute();
break;
case R.id.btnCancel:
myAsyncTask.cancel(true);
break;
default:
break;
}
}
private class MyAsyncTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
mTVShow.setText("加载中....");
}
@Override
protected String doInBackground(String... strings) {
int count = 0;
while (count < 99) {
count += 1;
// 可调用publishProgress()显示进度, 之后将执行onProgressUpdate()
publishProgress(count);
try {
Thread.sleep(1 * 50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progresses) {
super.onProgressUpdate(progresses);
mProgress.setProgress(progresses[0]);
mTVShow.setText("loading...." + progresses[0] + "%");
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// 执行完毕后,则更新UI
mTVShow.setText("加载完毕");
}
@Override
protected void onCancelled() {
super.onCancelled();
mTVShow.setText("已取消加载");
mProgress.setProgress(0);
}
}
}
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始加载" />
<TextView
android:id="@+id/textShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="还没开始加载" />
<ProgressBar
android:id="@+id/progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0" />
<Button
android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取消加载" />