private class MyAyncTask extends AsyncTask<String, Integer, String>{
//初始化UI
@Override
protected void onPreExecute() {
super.onPreExecute();
mSeekBar.setProgress(0);
mSeekBar.setMax(100);
mTextView.setText("loading ...");
}
//后台操作
@Override
protected String doInBackground(String... params) {
try {
// 1. 构造URL对象
String path = params[0];
URL url = new URL(path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setRequestProperty("Accept-Encoding", "identity");
int code = urlConnection.getResponseCode();
// 200 OK 302 found 404 not fount 500 内部错误
if (code == 200) {
// 获取内容长度,需要指定RequestProperty
int nMaxLen = urlConnection.getContentLength();
int nLen = 0;
// 4.1 读取信息
InputStream inputStream = urlConnection.getInputStream();
byte[] bytes = new byte[50];
int iReadSize = 0;
// 创建字节流对象,用于保存输入流的信息
ByteArrayOutputStream byteObj = new ByteArrayOutputStream();
while (iReadSize != -1) {
// 循环读取数据信息,每次读取1024字节,会自动移动指针
// 第二个参数指的值字节数组的起始偏移
iReadSize = inputStream.read(bytes, 0, 50);
if (iReadSize == -1) break;
// 计算已经读取的长度
this.publishProgress((int) (((float) nLen / (float) nMaxLen) * 100));
byteObj.write(bytes, 0, iReadSize);
}
inputStream.close();
String strings = new String(byteObj.toByteArray());
return strings;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mSeekBar.setProgress(values[0]);
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
mTextView.setText(s);
}
}
Android源68,69,70
最新推荐文章于 2023-05-07 16:47:37 发布