1。既然下载图片,网络权限一定要给的 可别忘了
在AndroidManifest.xml中加入一下权限:
<uses-permission android:name="android.permission.INTERNET"/>
2。开始写下载图片和加载图片的工具类
/**
* Created by GRR on 2016/2/16.
*/
public class BitmapUtil {
/**
* HttpURLConnection下载图片并转化为bitmap
* @param imgUrl
* @return
*/
public static Bitmap getBitmap(String imgUrl) {
try {
//生成url
URL url = new URL(imgUrl);
//建立连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置超时 5s
connection.setConnectTimeout(5000);
//设置请求方法
connection.setRequestMethod("GET");
//连接成功
if (connection.getResponseCode()==200){
//获取输入流
InputStream in=connection.getInputStream();
//将流转化为bitmap
Bitmap bitmap= BitmapFactory.decodeStream(in);
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* imageview加载图片
* @param imageView
* @param bitmap
*/
public static void setImageView(ImageView imageView,Bitmap bitmap){
imageView.setImageBitmap(bitmap);
}
}
3。在Activity中显示图片 记得要开启子线程下载图片
public class MyActivity extends Activity {
ImageView imageView;
//下载地址
private String imaUrl="http://img0.imgtn.bdimg.com/it/u=3305752239,589815963&fm=21&gp=0.jpg";
private static final int BITMAP_NOT_NULL=0;
private static final int BITMAP_NULL=1;
private Handler mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case BITMAP_NOT_NULL://图片下载成功
Bitmap bitmap=(Bitmap)msg.obj;
BitmapUtil.setImageView(imageView,bitmap);
break;
case BITMAP_NULL://图片为空
break;
}
}
};
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();//初始化view
initData();//初始化数据
}
private void initView(){
imageView=(ImageView)findViewById(R.id.imageview);
}
private void initData(){
new Thread(){
@Override
public void run() {
super.run();
Bitmap bitmap=BitmapUtil.getBitmap(imaUrl);
if (bitmap!=null){
Message msg=new Message();
msg.what=BITMAP_NOT_NULL;
msg.obj=bitmap;
mHandler.sendMessage(msg);
}else{
mHandler.sendEmptyMessage(BITMAP_NULL);
}
}
}.start();
}
}
这样 就用原始的方法把图片加载出来了