标签:
package com.example.day7_practise;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity{
ImageView iv;
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView) findViewById(R.id.imageView1);
btn1=(Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
DownloadTask mTask = new DownloadTask();
String uri = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png";
mTask.execute(uri);
}
});
}
private class DownloadTask extends AsyncTask<String,Integer , Bitmap> {
ProgressDialog pDialog;
/**
* 参数1为doInBackground参数 由onClick方法中execute设置的参数
* 参数2为onProgressUpdate参数 由publishProgress(方法用在子线程中)传入。
* 参数3为onPostExecute参数 由doInBackground方法返传入
*/
// (主线程)在子线程执行之前调用它
@Override
protected void onPreExecute() {
//创建对话框
pDialog = new ProgressDialog(MainActivity.this);
//创建标题栏
pDialog.setTitle("下载图片");
//设置进度条样式
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMax(100);
pDialog.setMessage("正在下载");
pDialog.show();
}
// (子线程)执行子线程
@Override
protected Bitmap doInBackground(String... params) {
HttpURLConnection conn = null;
URL url;
try {
url = new URL(params[0]);
conn=(HttpURLConnection) url.openConnection();
int code=conn.getResponseCode();
if(code==200){
//取出流中图片信息解析成图片
Bitmap bmap=BitmapFactory.decodeStream(conn.getInputStream());
return bmap;
}else {
throw new RuntimeException("网络访问失败");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(conn!=null){
conn.disconnect();
conn=null;
}
}
return null;
}
// (主线程)在子线程执行时更新UI界面
@Override
protected void onProgressUpdate(Integer... values) {
//pDialog.setProgress(value);
}
// (主线程)在子线程执行之后执行,擦屁股专用
@Override
protected void onPostExecute(Bitmap bmap) {
if(bmap==null){
Toast.makeText(MainActivity.this, "下载失败", 0).show();
}else {
iv.setImageBitmap(bmap);
}
pDialog.cancel();
}
}
}
标签:
原文地址:http://www.cnblogs.com/booty/p/5143786.html