跟新UI第一种方式
MainActivity类
代码
public class MainActivity extends Activity {
//下载图片的地址URL
private String url = "http://litchiapi.jstv.com/Attachs/Top/11949/e650e0201de541d2ba91dca202b0fcfe.jpg";
private ImageView imageview;
private ProgressDialog progressDialog;
//更新UI 主线程
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
progressDialog.show();
break;
case 2:
imageview.setImageBitmap((Bitmap)msg.obj);
break;
case 3:
//关闭下载进度条
progressDialog.dismiss();
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageview = (ImageView) this.findViewById(R.id.imageview);
// 下载加载进度条
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("提示");
progressDialog.setIcon(R.drawable.ic_launcher);
progressDialog.setMessage("正在下载...");
//下载图片方法1
// 子线程
new Thread(new Runnable() {
@Override
public void run() {
// 显示下载进度条
handler.sendEmptyMessage(1);//发送一个空消息
try {
Thread.sleep(1000);//休眠时间长点 保证下载进度条显示才下载图片
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 下载图片
byte[] img_data = downimag();
Bitmap bitmap = BitmapFactory.decodeByteArray(img_data, 0,
img_data.length);
Message message = Message.obtain();
message.what = 2;
message.obj = bitmap;
//图片数据下载完成消息
handler.sendMessage(message);
//关闭下载进度条消息
handler.sendEmptyMessage(3);
}
}).start();
}
private byte[] downimag() {
HttpGet get = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toByteArray(response.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
===================================
跟新UI第二种方式
MainActivity类
代码
public class MainActivity extends Activity {
private String url = "http://litchiapi.jstv.com/Attachs/Top/11949/e650e0201de541d2ba91dca202b0fcfe.jpg";
private ImageView imageview;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageview = (ImageView) this.findViewById(R.id.imageview);
//开启子线程
new Thread (new Runnable() {
@Override
public void run() {
// 下载图片
byte[] img_data = downimag();
final Bitmap bitmap = BitmapFactory.decodeByteArray(img_data, 0,
img_data.length);
//更新UI第二种方法
//使用handle.post方法
handler.post(new Runnable() {
@Override
public void run() {
//在这里更新UI-- 主线程
imageview.setImageBitmap(bitmap);
}
});
}
}).start();
}
private byte[] downimag() {
HttpGet get = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toByteArray(response.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}