写了快大半年android了,发现写的博客数量太少了。很多东西其实都可以总结记录一下的,哎,只怪太懒,难得今天这么休闲,就一口气了。其实这篇文章介绍的主题也是今天才搞定的,初衷是,服务端发送富文本标签到客户端可以显示,TextView本来是可以显示图片的,比如微信中插入图片类似,问题是什么呢,图片异步加载的实现方式,客户端想做到用户体验非常爽需要花费大量功夫处理。废话多了就啰嗦了,写了一个自己比较好用的类,先演示使用方法吧,想用的人是不关心你的实现。

TextView htmlTextView = (TextView)findViewById(R.id.text_view);

Spanned sp = Html.fromHtml(content,

new HtmlImageGetter(htmlTextView, "/esun_msg", _defaultLoading),

null);

htmlTextView.setText(sp);

介绍一下HtmlImageGetter析构中的三个参数,第一个是Textview对象,主要是为了加载完成后刷新才能显示图片用,第二个参数是,加载出来的图片保存到sd卡的目录,第三个参数是图片未加载时候先显示的加载中Drawable对象。怎么样,用起来还算ok吧,因为图快速实现,所以几乎都忽略了注释,下面就直接来类了

public class HtmlImageGetter implements Html.ImageGetter{

private TextView _htmlText;

private String _imgPath;

private Drawable _defaultDrawable;

public HtmlImageGetter(TextView htmlText, String imgPath, Drawable defaultDrawable){

_htmlText = htmlText;

_imgPath = imgPath;

_defaultDrawable = defaultDrawable;

}

@Override

public Drawable getDrawable(String imgUrl) {

String imgKey = Common.md5(imgUrl);

String path = Environment.getExternalStorageDirectory() + _imgPath;

FileUtil.createPath(path);

String[] ss = imgUrl.split("\\.");

String imgX = ss[ss.length-1];

imgKey = path+"/" + imgKey+"."+imgX;

if(FileUtil.exists(imgKey)){

Drawable drawable = FileUtil.getImageDrawable(imgKey);

if(drawable != null){

drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

return drawable;

}else{

Common.log("load img:"+imgKey+":null");

}

}

URLDrawable urlDrawable = new URLDrawable(_defaultDrawable);

new AsyncThread(urlDrawable).execute(imgKey, imgUrl);

return urlDrawable;

}

private class AsyncThread extends AsyncTask{

private String imgKey;

private URLDrawable _drawable;

public AsyncThread(URLDrawable drawable){

_drawable = drawable;

}

@Override

protected Drawable doInBackground(String... strings) {

imgKey = strings[0];

InputStream inps = NetWork.getInputStream(strings[1]);

if(inps == null) return _drawable;

FileUtil.saveFile(imgKey, inps);

Drawable drawable = Drawable.createFromPath(imgKey);

return drawable;

}

public void onProgressUpdate(Integer... value) {

}

@Override

protected void onPostExecute(Drawable result) {

_drawable.setDrawable(result);

_htmlText.setText(_htmlText.getText());

}

}

public class URLDrawable extends BitmapDrawable {

private Drawable drawable;

public URLDrawable(Drawable defaultDraw){

setDrawable(defaultDraw);

}

private void setDrawable(Drawable ndrawable){

drawable = ndrawable;

drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable

.getIntrinsicHeight());

setBounds(0, 0, drawable.getIntrinsicWidth(), drawable

.getIntrinsicHeight());

}

@Override

public void draw(Canvas canvas) {

drawable.draw(canvas);

}

}

}

在代码中有两个封装的方法,一个是网络请求图片和保存图片到sd卡中,就简单贴贴代码了,没甚么技术含量

public class NetWork {

public static String getHttpData(String baseUrl){

return getHttpData(baseUrl, "GET", "", null);

}

public static String postHttpData(String baseUrl, String reqData){

return getHttpData(baseUrl, "POST", reqData, null);

}

public static String postHttpData(String baseUrl, String reqData, HashMappropertys){

return getHttpData(baseUrl, "POST", reqData, propertys);

}

/**

* 获取赛事信息

* @return

*/

public static String getHttpData(String baseUrl, String method, String reqData, HashMappropertys){

String data = "", str;

PrintWriter outWrite = null;

InputStream inpStream = null;

BufferedReader reader = null;

HttpURLConnection urlConn = null;

try{

URL url = new URL(baseUrl);

urlConn = (HttpURLConnection)url.openConnection();

//启用gzip压缩

urlConn.addRequestProperty("Accept-Encoding", "gzip, deflate");

urlConn.setRequestMethod(method);

urlConn.setDoOutput(true);

urlConn.setConnectTimeout(Config.TIME_OUT);

if(propertys != null && !propertys.isEmpty()){

Iterator> props = propertys.entrySet().iterator();

Map.Entryentry;

while (props.hasNext()){

entry = props.next();

urlConn.setRequestProperty(entry.getKey(), entry.getValue());

}

}

outWrite = new PrintWriter(urlConn.getOutputStream());

outWrite.print(reqData);

outWrite.flush();

urlConn.connect();

//获取数据流

inpStream = urlConn.getInputStream();

String encode = urlConn.getHeaderField("Content-Encoding");

//如果通过gzip

if(encode !=null && encode.indexOf("gzip") != -1){

Log.d(Config.LOG_TAG, "get data :" + encode);

inpStream = new GZIPInputStream(inpStream);

}else if(encode != null && encode.indexOf("deflate") != -1){

inpStream = new InflaterInputStream(inpStream);

}

reader = new BufferedReader(new InputStreamReader(inpStream));

while((str = reader.readLine()) != null){

data += str;

}

}catch (MalformedURLException ex){

Common.errorReport(ex);

}catch (IOException ex){

Common.errorReport(ex);

}finally{

if(reader !=null && urlConn!=null){

try {

outWrite.close();

inpStream.close();

reader.close();

urlConn.disconnect();

} catch (IOException ex) {

Common.errorReport(ex);

}

}

}

Log.d(Config.LOG_TAG, "[Http data]["+baseUrl+"]:" + data);

return data;

}

/**

* 获取Image信息

* @return

*/

public static Bitmap getBitmapData(String imgUrl){

Bitmap bmp = null;

Log.d(Config.LOG_TAG, "get imgage:"+imgUrl);

InputStream inpStream = null;

try{

HttpGet http = new HttpGet(imgUrl);

HttpClient client = new DefaultHttpClient();

HttpResponse response = (HttpResponse)client.execute(http);

HttpEntity httpEntity = response.getEntity();

BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);

//获取数据流

inpStream = bufferedHttpEntity.getContent();

bmp = BitmapFactory.decodeStream(inpStream);

}catch (Exception ex){

Common.errorReport(ex);

}finally{

if(inpStream !=null){

try {

inpStream.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

return bmp;

}

/**

* 获取url的InputStream

* @param urlStr

* @return

*/

public static InputStream getInputStream(String urlStr){

Log.d(Config.LOG_TAG, "get http input:"+urlStr);

InputStream inpStream = null;

try{

HttpGet http = new HttpGet(urlStr);

HttpClient client = new DefaultHttpClient();

HttpResponse response = (HttpResponse)client.execute(http);

HttpEntity httpEntity = response.getEntity();

BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);

//获取数据流

inpStream = bufferedHttpEntity.getContent();

}catch (Exception ex){

Common.errorReport(ex);

}finally{

if(inpStream !=null){

try {

inpStream.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

return inpStream;

}

}

package com.esun.trade.lib;

import java.io.*;

import android.graphics.drawable.BitmapDrawable;

import android.graphics.drawable.Drawable;

import android.os.Environment;

import android.util.Log;

import com.esun.trade.inc.Config;

public class FileUtil {

private static int FILE_SIZE = 4*1024;

public static boolean hasSdcard(){

String status = Environment.getExternalStorageState();

if(status.equals(Environment.MEDIA_MOUNTED)){

return true;

}

return false;

}

public static boolean createPath(String path){

File f = new File(path);

if(!f.exists()){

Boolean o = f.mkdirs();

Log.i(Config.LOG_TAG, "create dir:"+path+":"+o.toString());

return o;

}

return true;

}

public static boolean exists(String file){

return new File(file).exists();

}

public static File saveFile(String file, InputStream inputStream){

File f = null;

OutputStream outSm = null;

try{

f = new File(file);

String path = f.getParent();

if(!createPath(path)){

Log.e(Config.LOG_TAG, "can't create dir:"+path);

return null;

}

if(!f.exists()){

f.createNewFile();

}

outSm = new FileOutputStream(f);

byte[] buffer = new byte[FILE_SIZE];

while((inputStream.read(buffer)) != -1){

outSm.write(buffer);

}

outSm.flush();

}catch (IOException ex) {

Common.errorReport(ex);

return null;

}finally{

try{

if(outSm != null) outSm.close();

}catch (IOException ex) {

Common.errorReport(ex);

}

}

Common.log("[FileUtil]save file:"+file+":"+Boolean.toString(f.exists()));

return f;

}

public static Drawable getImageDrawable(String file){

if(!exists(file)) return null;

try{

InputStream inp = new FileInputStream(new File(file));

return BitmapDrawable.createFromStream(inp, "img");

}catch (Exception ex){

Common.errorReport(ex);

}

return null;

}

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐