您的位置:首页 > 理论基础 > 计算机网络

android:自定义imageview,可显示网络图片

2013-10-06 11:45 519 查看
package com.example.test.widget;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
* 自定义imageview,可显示网络图片
*
* @author huaf22@gmail.com
* @date 2013-10-5 下午8:21:24
*/
public class NetImageView extends ImageView {
public NetImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public NetImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}

Handler handler = new Handler() {

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
byte[] data = (byte[]) msg.obj;
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
setImageBitmap(bitmap);// 显示图片
}
}

};

public void setNetImage(final String path) {
new Thread(new Runnable() {
public void run() {
handler.sendMessage(handler.obtainMessage(21, httpServer(path)));
}
}).start();
}

private byte[] httpServer(String imagepath) {
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
conn = (HttpURLConnection) new URL(imagepath).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
is = ((URLConnection) conn).getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
return os.toByteArray();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}


使用方法:

<com.example.test.widget.NetImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="80dp"
android:src="@drawable/ic_launcher" />


private NetImageView imageview = null;

private String imagepath="http://192.168.1.102:8080/APP/usrIcon/002.jpg";

imageview = (NetImageView) findViewById(R.id.imageView1);

imageview.setNetImage(imagePath);


缺点:

1.不能加载多个大图片,会产生内存溢出

2.没有线程数量控制,加载N多图片时,会产生N多线程

我会在以后的版本里继续改进。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: