当前位置:  编程技术>移动开发

android上的一个网络接口和图片缓存框架enif简析

    来源: 互联网  发布时间:2014-10-12

    本文导语:  1.底层网络接口采用apache的httpclient连接池框架; 2.图片缓存采用基于LRU的算法; 3.网络接口采用监听者模式; 4.包含图片的OOM处理(及时回收处理技术的应用); 图片核心处理类:CacheView.java 代码如下: package xiaogang.enif.image; ...

1.底层网络接口采用apache的httpclient连接池框架;
2.图片缓存采用基于LRU的算法;
3.网络接口采用监听者模式;
4.包含图片的OOM处理(及时回收处理技术的应用);

图片核心处理类:CacheView.java
代码如下:

package xiaogang.enif.image;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.concurrent.RejectedExecutionException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import xiaogang.enif.utils.HttpManager;
import xiaogang.enif.utils.IOUtils;
import xiaogang.enif.utils.LogUtils;
import xiaogang.enif.utils.LruCache;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CacheView extends ImageView {
private static final int DEFAULT_RES_ID = 0;
private int mDefaultImage = DEFAULT_RES_ID;
private static LruCache mLruCache;
private static HashMap mResImage;
private Context mContext;
private LogUtils mLog = LogUtils.getLog(CacheView.class);
public CacheView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public CacheView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CacheView(Context context) {
super(context);
init(context);
}
private void init(Context context) {
mContext = context;
if (mLruCache == null) {
final int cacheSize = getCacheSize(context);
mLruCache = new LruCache(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in bytes rather than
// number of items.
return bitmap.getRowBytes() * bitmap.getHeight();
}
@Override
protected void entryRemoved(boolean evicted, String key, Bitmap oldValue,
Bitmap newValue) {
if (evicted && oldValue != null && !oldValue.isRecycled()) {
oldValue.recycle();
oldValue = null;
}
}
};
}
if (mResImage == null) {
mResImage = new HashMap();
}
}
@Override
protected void onDraw(Canvas canvas) {
BitmapDrawable drawable = (BitmapDrawable)getDrawable();
if (drawable == null) {
setDefaultImage();
} else {
if (drawable.getBitmap() == null || drawable.getBitmap().isRecycled()) {
setDefaultImage();
}
}
try {
super.onDraw(canvas);
} catch(RuntimeException ex) {
}
}
public void setImageUrl(/tech-mobile-dev/String url, int resId/index.html) {
setTag(url);
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap == null || bitmap.isRecycled()) {
mDefaultImage = resId;
setDefaultImage();
try {
new DownloadTask().execute(url);
} catch (RejectedExecutionException e) {
// do nothing, just keep not crash
}
} else {
setImageBitmap(bitmap);
}
}
private void setDefaultImage() {
if (mDefaultImage != DEFAULT_RES_ID) {
setImageBitmap(getDefaultBitmap(mContext));
}
}
private Bitmap getDefaultBitmap(Context context) {
SoftReference loading = mResImage.get(mDefaultImage);
if (loading == null || loading.get() == null || loading.get().isRecycled()) {
loading = new SoftReference(BitmapFactory.decodeResource(
context.getResources(), mDefaultImage));
mResImage.put(mDefaultImage, loading);
}
return loading.get();
}
private class DownloadTask extends AsyncTask {
private String mParams;
@Override
public Bitmap doInBackground(String... params) {
mParams = params[0];
final Bitmap bm = download(mParams);
addBitmapToCache(mParams, bm);
return bm;
}
@Override
public void onPostExecute(Bitmap bitmap) {
String tag = (String)getTag();
if (!TextUtils.isEmpty(tag) && tag.equals(mParams)) {
if (bitmap != null) {
setImageBitmap(bitmap);
}
}
}
};
/*
* An InputStream that skips the exact number of bytes provided, unless it
* reaches EOF.
*/
static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
@Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int b = read();
if (b < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
private Bitmap download(String url) {
InputStream in = null;
HttpEntity entity = null;
Bitmap bmp = null;
try {
final HttpGet get = new HttpGet(url);
final HttpResponse response = HttpManager.execute(mContext, get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
in = entity.getContent();
try {
bmp = getDecodeBitmap(in, url);
} catch (OutOfMemoryError err) {
Runtime.getRuntime().gc();
bmp = getDecodeBitmap(in, url);
}
} else {
get.abort();
return bmp;
}
addBitmapToCache(url, bmp);
} catch (IOException e) {
return bmp;
} finally {
IOUtils.closeStream(in);
}
return bmp;
}
private final Bitmap getDecodeBitmap(InputStream in, String url) {
Options options = new Options();
options.inPurgeable = true;
options.inInputShareable = true;
return BitmapFactory.decodeStream(new FlushedInputStream(in), null, options);
}
private final void addBitmapToCache(String url, Bitmap bitmap) {
if (bitmap != null) {
mLruCache.put(url, bitmap);
Runtime.getRuntime().gc();
}
}
private final Bitmap getBitmapFromCache(String url) {
return mLruCache.get(url);
}
private int getCacheSize(Context context) {
// According to the phone memory, set a proper cache size for LRU cache
// dynamically.
final ActivityManager am = (ActivityManager)context
.getSystemService(Context.ACTIVITY_SERVICE);
final int memClass = am.getMemoryClass();
int cacheSize;
if (memClass

    
 
 
 
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • Android 功能测试框架 calabash-android
  • Android自动化测试框架 Cafe
  • android的IOC框架 absir-android
  • Android日志框架 SLF4J Android
  • Android 主题框架 ColorTheme
  • Android3D应用与游戏开发框架 JQGL
  • Android集成测试框架 Robotium
  • Android的开发框架 mobilelite
  • Android 本地服务器框架 node-android
  • android框架 SAF
  • Android多媒体框架 OpenCore
  • Android单元测试框架 Robolectric
  • Android持久层框架 Androrm
  • Android应用开发框架 KJFrameForAndroid
  • Android 混合应用开发框架 karura
  • Android推送框架 androidpn
  • Android 测试框架 RoboSpock
  • Android 测试框架 uiautomator
  • Android轻量级ORM框架 ActiveAndroid
  • Android推送框架 androidpn iis7站长之家
  • 申请Android Map 的API Key(v2)的最新申请方式(SHA1密钥)
  • Android瀑布流实例 android_waterfall
  • Android开发需要的几点注意事项总结
  • Android系统自带样式 (android:theme)
  • android 4.0 托管进程介绍及优先级和回收机制
  • Android网络共享软件 Android Wifi Tether
  • Android访问与手机通讯相关类的介绍
  • Android 图标库 Android GraphView
  • Android及andriod无线网络Wifi开发的几点注意事项
  • 轻量级Android开发工具 Android Tools
  • Android 2.3 下StrictMode介绍




  • 特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3