Java代码如下:
xml布局:
<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" >
<ProgressBar
android:id="@+id/pb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载图片" />
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
下面是MainActivity
public class MainActivity extends Activity {
private Button btn;
private ImageView img;
private ProgressBar pb;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) this.findViewById(R.id.btn);
img = (ImageView) this.findViewById(R.id.img);
tv = (TextView) this.findViewById(R.id.info);
pb=(ProgressBar) this.findViewById(R.id.pb);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Task(pb, tv, img).execute("http://pic33.nipic.com/20131008/13661616_190558208000_2.jpg");
}
});
}
}
下面的是主要代码功能实现
String 是 doInBackground方法的参数
Integer是 onProgressUpdate方法的参数
Bitmap 是onPostExecute方法的参数,也是doInBackground要返回的值
public class Task extends AsyncTask<String, Integer, Bitmap> {
private ProgressBar pb;
private TextView tv;
private ImageView img;
private int mAX;
public Task(ProgressBar pb, TextView tv, ImageView img) {
this.pb = pb;
this.tv = tv;
this.img = img;
}
@Override
protected Bitmap doInBackground(String... params) { //后台运行,执行请求
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
mAX = conn.getContentLength();
pb.setMax(mAX);
InputStream is = conn.getInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] bys = new byte[1024];
int len = 0;
int num = 0;
while ((len = is.read(bys)) != -1) {
os.write(bys, 0, len);
num += len;
publishProgress(num);
}
bitmap = BitmapFactory.decodeByteArray(os.toByteArray(), 0, mAX);
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap; //返回的数据是onPostExecute方法的参数
}
@Override
protected void onPreExecute() {//下载之前的准备
tv.setText("准备下载中...");
super.onPreExecute();
}
@Override
protected void onPostExecute(Bitmap result) { //下载完成的结果,
tv.setText("下载完成");
img.setImageBitmap(result);
super.onPostExecute(result);
}
@Override
protected void onProgressUpdate(Integer... values) { //刷新ui
tv.setText("下载中..." + values[0]);
pb.setProgress(values[0]);
super.onProgressUpdate(values);
}
}