HttpURLConnection conn = (HttpURLConnection) url.openConnection();
执行此方法用来开辟一个URL请求,该请求在Android4.0版本以后需要放到子线程中实现,主线程已不支持httprequest请求(android2.3仍然支持此项)
因为在子线程中不可以对view操作,因为view是在主线程创建的,需要在子线程中以消息的形式通知主线程
package com.example.imageviewdemo;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class MainActivity extends Activity {
private Handler mHandler;
private Button btn;
private ImageView imv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button) findViewById(R.id.btn_download);
imv=(ImageView) findViewById(R.id.imv_download);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
updateUI();
mHandler=new Handler(){
public void handleMessage(android.os.Message msg){
if(msg.what==1){
imv.setImageBitmap((Bitmap)msg.obj);
}
}
};
}
});
}
private void updateUI(){
new Thread(){
public void run(){
try {
URL url=new URL("http://img0.bdstatic.com/img/image/shouye/mxzyq-11795342220.jpg");
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code=conn.getResponseCode();
if(code==200){
InputStream is=conn.getInputStream();
Bitmap bitmap=BitmapFactory.decodeStream(is);
Message msg=new Message();
msg.what=1;
msg.obj=bitmap;
mHandler.sendMessage(msg);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}