MainActivity
package com.example.threadlean;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
private TextView show;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = findViewById(R.id.show);
progressBar = findViewById(R.id.pro);
}
public void download(View view) throws MalformedURLException {
DownTask task = new DownTask(this, progressBar);
task.execute(new URL("http://www.crazyit.org/index.php"));
}
//1.输入参数类型
//2.进度类型
//3.完成后返回值类型
class DownTask extends AsyncTask<URL, Integer, String> {
private ProgressBar progressBar;
//定义记录已经读取的行数
int hasRead = 0;
Context mContext;
public DownTask(Context context, ProgressBar progressBar) {
this.mContext = context;
this.progressBar = progressBar;
}
//线程将要完成的任务
@Override
protected String doInBackground(URL... urls) {
StringBuilder sb = new StringBuilder();
try {
URLConnection urlConnection = urls[0].openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
hasRead++;
//返回进度
publishProgress(hasRead);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//线程完成后调用返回doInBackground的结果
@Override
protected void onPostExecute(String s) {
show.setText(s);
progressBar.setVisibility(View.INVISIBLE);
}
//doInBackground之前执行
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(120);
}
//当doInBackground()->publishProgress()执行后触发
@Override
protected void onProgressUpdate(Integer... values) {
show.setText("读取" + values[0] + "行");
progressBar.setProgress(values[0]);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="download" />
<ProgressBar
android:id="@+id/pro"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>