Android 内存溢出解决方案(OOM) 整理总结
来源:互联网 发布:数据库营销是什么 编辑:程序博客网 时间:2024/05/16 19:15
http://mzh3344258.blog.51cto.com/1823534/804237
- Object o=new Object();
- Object o1=o;
- o=null;
- o1=null
- String abc=new String("abc"); //1
- SoftReference<String> abcSoftRef=new SoftReference<String>(abc); //2
- WeakReference<String> abcWeakRef = new WeakReference<String>(abc); //3
- abc=null; //4
- abcSoftRef.clear();//5
- Reference(T paramT, ReferenceQueue<? super T>paramReferenceQueue)
- A obj = new A();
- Refenrence sr = new SoftReference(obj);
- //引用时
- if(sr!=null){
- obj = sr.get();
- }else{
- obj = new A();
- sr = new SoftReference(obj);
- }
- String abc=new String("abc");
- WeakReference<String> abcWeakRef = new WeakReference<String>(abc);
- abc=null;
- System.out.println("before gc: "+abcWeakRef.get());
- System.gc();
- System.out.println("after gc: "+abcWeakRef.get());
- A obj = new A();
- WeakReference wr = new WeakReference(obj);
- obj = null;
- //等待一段时间,obj对象就会被垃圾回收
- ...
- if (wr.get()==null) {
- System.out.println("obj 已经被清除了 ");
- } else {
- System.out.println("obj 尚未被清除,其信息是 "+obj.toString());
- }
- ...
- }
- import java.lang.ref.PhantomReference;
- import java.lang.ref.Reference;
- import java.lang.ref.ReferenceQueue;
- import java.lang.reflect.Field;
- public class Test {
- public static boolean isRun = true;
- public static void main(String[] args) throws Exception {
- String abc = new String("abc");
- System.out.println(abc.getClass() + "@" + abc.hashCode());
- final ReferenceQueue referenceQueue = new ReferenceQueue<String>();
- new Thread() {
- public void run() {
- while (isRun) {
- Object o = referenceQueue.poll();
- if (o != null) {
- try {
- Field rereferent = Reference.class
- .getDeclaredField("referent");
- rereferent.setAccessible(true);
- Object result = rereferent.get(o);
- System.out.println("gc will collect:"
- + result.getClass() + "@"
- + result.hashCode());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- }.start();
- PhantomReference<String> abcWeakRef = new PhantomReference<String>(abc,
- referenceQueue);
- abc = null;
- Thread.currentThread().sleep(3000);
- System.gc();
- Thread.currentThread().sleep(3000);
- isRun = false;
- }
- }
- @SuppressWarnings("unused")
- private Bitmap copressImage(String imgPath){
- File picture = new File(imgPath);
- Options bitmapFactoryOptions = new BitmapFactory.Options();
- //下面这个设置是将图片边界不可调节变为可调节
- bitmapFactoryOptions.inJustDecodeBounds = true;
- bitmapFactoryOptions.inSampleSize = 2;
- int outWidth = bitmapFactoryOptions.outWidth;
- int outHeight = bitmapFactoryOptions.outHeight;
- bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
- bitmapFactoryOptions);
- float imagew = 150;
- float imageh = 150;
- int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight
- / imageh);
- int xRatio = (int) Math
- .ceil(bitmapFactoryOptions.outWidth / imagew);
- if (yRatio > 1 || xRatio > 1) {
- if (yRatio > xRatio) {
- bitmapFactoryOptions.inSampleSize = yRatio;
- } else {
- bitmapFactoryOptions.inSampleSize = xRatio;
- }
- }
- bitmapFactoryOptions.inJustDecodeBounds = false;
- bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
- bitmapFactoryOptions);
- if(bmap != null){
- //ivwCouponImage.setImageBitmap(bmap);
- return bmap;
- }
- return null;
- }
- package com.lvguo.scanstreet.activity;
- import java.io.File;
- import java.lang.ref.SoftReference;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.res.TypedArray;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.BitmapFactory.Options;
- import android.os.Bundle;
- import android.view.View;
- import android.view.ViewGroup;
- import android.view.WindowManager;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemLongClickListener;
- import android.widget.BaseAdapter;
- import android.widget.Gallery;
- import android.widget.ImageView;
- import android.widget.Toast;
- import com.lvguo.scanstreet.R;
- import com.lvguo.scanstreet.data.ApplicationData;
- /**
- * @Title: PhotoScanActivity.java
- * @Description: 照片预览控制类
- * @author XiaoMa
- */
- public class PhotoScanActivity extends Activity {
- private Gallery gallery ;
- private List<String> ImageList;
- private List<String> it ;
- private ImageAdapter adapter ;
- private String path ;
- private String shopType;
- private HashMap<String, SoftReference<Bitmap>> imageCache = null;
- private Bitmap bitmap = null;
- private SoftReference<Bitmap> srf = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FULLSCREEN);
- setContentView(R.layout.photoscan);
- Intent intent = this.getIntent();
- if(intent != null){
- if(intent.getBundleExtra("bundle") != null){
- Bundle bundle = intent.getBundleExtra("bundle");
- path = bundle.getString("path");
- shopType = bundle.getString("shopType");
- }
- }
- init();
- }
- private void init(){
- imageCache = new HashMap<String, SoftReference<Bitmap>>();
- gallery = (Gallery)findViewById(R.id.gallery);
- ImageList = getSD();
- if(ImageList.size() == 0){
- Toast.makeText(getApplicationContext(), "无照片,请返回拍照后再使用预览", Toast.LENGTH_SHORT).show();
- return ;
- }
- adapter = new ImageAdapter(this, ImageList);
- gallery.setAdapter(adapter);
- gallery.setOnItemLongClickListener(longlistener);
- }
- /**
- * Gallery长按事件操作实现
- */
- private OnItemLongClickListener longlistener = new OnItemLongClickListener() {
- @Override
- public boolean onItemLongClick(AdapterView<?> parent, View view,
- final int position, long id) {
- //此处添加长按事件删除照片实现
- AlertDialog.Builder dialog = new AlertDialog.Builder(PhotoScanActivity.this);
- dialog.setIcon(R.drawable.warn);
- dialog.setTitle("删除提示");
- dialog.setMessage("你确定要删除这张照片吗?");
- dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- File file = new File(it.get(position));
- boolean isSuccess;
- if(file.exists()){
- isSuccess = file.delete();
- if(isSuccess){
- ImageList.remove(position);
- adapter.notifyDataSetChanged();
- //gallery.setAdapter(adapter);
- if(ImageList.size() == 0){
- Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoSizeZero), Toast.LENGTH_SHORT).show();
- }
- Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoDelSuccess), Toast.LENGTH_SHORT).show();
- }
- }
- }
- });
- dialog.setNegativeButton("取消",new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- dialog.create().show();
- return false;
- }
- };
- /**
- * 获取SD卡上的所有图片文件
- * @return
- */
- private List<String> getSD() {
- /* 设定目前所在路径 */
- File fileK ;
- it = new ArrayList<String>();
- if("newadd".equals(shopType)){
- //如果是从查看本人新增列表项或商户列表项进来时
- fileK = new File(ApplicationData.TEMP);
- }else{
- //此时为纯粹新增
- fileK = new File(path);
- }
- File[] files = fileK.listFiles();
- if(files != null && files.length>0){
- for(File f : files ){
- if(getImageFile(f.getName())){
- it.add(f.getPath());
- Options bitmapFactoryOptions = new BitmapFactory.Options();
- //下面这个设置是将图片边界不可调节变为可调节
- bitmapFactoryOptions.inJustDecodeBounds = true;
- bitmapFactoryOptions.inSampleSize = 5;
- int outWidth = bitmapFactoryOptions.outWidth;
- int outHeight = bitmapFactoryOptions.outHeight;
- float imagew = 150;
- float imageh = 150;
- int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight
- / imageh);
- int xRatio = (int) Math
- .ceil(bitmapFactoryOptions.outWidth / imagew);
- if (yRatio > 1 || xRatio > 1) {
- if (yRatio > xRatio) {
- bitmapFactoryOptions.inSampleSize = yRatio;
- } else {
- bitmapFactoryOptions.inSampleSize = xRatio;
- }
- }
- bitmapFactoryOptions.inJustDecodeBounds = false;
- bitmap = BitmapFactory.decodeFile(f.getPath(),
- bitmapFactoryOptions);
- //bitmap = BitmapFactory.decodeFile(f.getPath());
- srf = new SoftReference<Bitmap>(bitmap);
- imageCache.put(f.getName(), srf);
- }
- }
- }
- return it;
- }
- /**
- * 获取图片文件方法的具体实现
- * @param fName
- * @return
- */
- private boolean getImageFile(String fName) {
- boolean re;
- /* 取得扩展名 */
- String end = fName
- .substring(fName.lastIndexOf(".") + 1, fName.length())
- .toLowerCase();
- /* 按扩展名的类型决定MimeType */
- if (end.equals("jpg") || end.equals("gif") || end.equals("png")
- || end.equals("jpeg") || end.equals("bmp")) {
- re = true;
- } else {
- re = false;
- }
- return re;
- }
- public class ImageAdapter extends BaseAdapter{
- /* 声明变量 */
- int mGalleryItemBackground;
- private Context mContext;
- private List<String> lis;
- /* ImageAdapter的构造符 */
- public ImageAdapter(Context c, List<String> li) {
- mContext = c;
- lis = li;
- TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
- mGalleryItemBackground = a.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0);
- a.recycle();
- }
- /* 几定要重写的方法getCount,传回图片数目 */
- public int getCount() {
- return lis.size();
- }
- /* 一定要重写的方法getItem,传回position */
- public Object getItem(int position) {
- return lis.get(position);
- }
- /* 一定要重写的方法getItemId,传并position */
- public long getItemId(int position) {
- return position;
- }
- /* 几定要重写的方法getView,传并几View对象 */
- public View getView(int position, View convertView, ViewGroup parent) {
- System.out.println("lis:"+lis);
- File file = new File(it.get(position));
- SoftReference<Bitmap> srf = imageCache.get(file.getName());
- Bitmap bit = srf.get();
- ImageView i = new ImageView(mContext);
- i.setImageBitmap(bit);
- i.setScaleType(ImageView.ScaleType.FIT_XY);
- i.setLayoutParams( new Gallery.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
- WindowManager.LayoutParams.WRAP_CONTENT));
- return i;
- }
- }
- }
- 1. InputStream is = this.getResources().openRawResource(R.drawable.pic1);
- BitmapFactory.Options options=new BitmapFactory.Options();
- options.inJustDecodeBounds = false;
- options.inSampleSize = 10; //width,hight设为原来的十分一
- Bitmap btp =BitmapFactory.decodeStream(is,null,options);
- 2. if(!bmp.isRecycle() ){
- bmp.recycle() //回收图片所占的内存
- system.gc() //提醒系统及时回收
- }
- /** 这个地方大家别搞混了,为了方便小马把两个贴一起了,使用的时候记得分开使用
- * 以最省内存的方式读取本地资源的图片
- */
- public static Bitmap readBitMap(Context context, int resId){
- BitmapFactory.Options opt = new BitmapFactory.Options();
- opt.inPreferredConfig = Bitmap.Config.RGB_565;
- opt.inPurgeable = true;
- opt.inInputShareable = true;
- //获取资源图片
- InputStream is = context.getResources().openRawResource(resId);
- return BitmapFactory.decodeStream(is,null,opt);
- }
- if(bitmapObject.isRecycled()==false) //如果没有回收
- bitmapObject.recycle();
- private final static floatTARGET_HEAP_UTILIZATION = 0.75f;
- 在程序onCreate时就可以调用
- VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
- 即可
- private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
- //设置最小heap内存为6MB大小
- VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);
蒙奇小路飞、wangchenze123、lzl_bs
12人
了这篇文章类别:安卓学习┆阅读(61364)┆评论(28) ┆ 返回博主首页┆返回博客首页
上一篇 Android模拟器小工具实现模拟传感器(详解) 下一篇 Android 动态壁纸引擎试刀学习(初识安卓引擎)
文章评论
<< 1 2 >> 页数 ( 1/2 )
2012-04-08 07:59:16
楼主真是好人,谢谢楼主
2012-04-09 09:21:43
回复 name_110:[2楼]
吼吼,我把所有遇到的人都当做朋友,加油,我们一起努力,奋斗!
吼吼,我把所有遇到的人都当做朋友,加油,我们一起努力,奋斗!
2012-06-18 13:17:05
我也遇到了这样的问题 谢谢
2012-06-19 17:48:44
回复 qq_Android:[4楼]
能帮到你是最好的,呵呵,一起学习!加油。。。^_^
能帮到你是最好的,呵呵,一起学习!加油。。。^_^
2012-09-28 15:53:37
说的好详细啊 不知道内存泄露的问题其他系统有没有这么严重 碰到过这种问题 那时候只是简单地缓存图片到本地 然后将图片进行压缩 但是感觉这个问题没有很好的解决办法 只是减小了发生的几率
2012-10-01 21:33:33
回复 coolismonster:[6楼]
呵呵,现在3.0版本以后有个LruCache,一般情况下使用动态内存分配就可以解决,如果还不行的话,可以试下用只缓存屏幕上显示的图片就可以了,如果高频率使用BitmapFactory.decode。。。。的话可以查找下ContentProvider做缓存,提高效率..希望对朋友有帮助! ^_^ O_O
呵呵,现在3.0版本以后有个LruCache,一般情况下使用动态内存分配就可以解决,如果还不行的话,可以试下用只缓存屏幕上显示的图片就可以了,如果高频率使用BitmapFactory.decode。。。。的话可以查找下ContentProvider做缓存,提高效率..希望对朋友有帮助! ^_^ O_O
2012-12-06 10:03:18
楼主好强大啊,又那么认真的发贴,楼主好人,谢谢楼主
2012-12-07 12:56:30
回复 初入江湖:[8楼]
吼吼,谢谢支持.....周末会发布更为经典的篇,欢迎到时支持哦,加油加油!生命在于折腾!!! 一起努力
吼吼,谢谢支持.....周末会发布更为经典的篇,欢迎到时支持哦,加油加油!生命在于折腾!!! 一起努力
2013-04-17 17:34:24
楼主有没有PhotoScanActivity的完整的代码?你这只粘一个类出来,看不太懂啊。
邮箱 : yangli_for_study@163.com
邮箱 : yangli_for_study@163.com
2013-04-17 19:08:18
回复 稚者杨力:[10楼]
你好。我粘出来的就是完整的类哦....其中有一些是公司里面的代码,所以可能兄弟你看起来感觉有点缺少,其实我粘出来的代码够你使用了,如果还有部分代码不懂的,直接加我扣扣,你问我回答你 929789081
你好。我粘出来的就是完整的类哦....其中有一些是公司里面的代码,所以可能兄弟你看起来感觉有点缺少,其实我粘出来的代码够你使用了,如果还有部分代码不懂的,直接加我扣扣,你问我回答你 929789081
2013-04-22 22:11:34
回复 华华世界:[11楼]
其实主要是SoftReference不了解,看过之后还是理解不了它是怎么用的。
网上也搜过好多Java的四种引用方式,没能找到一个完整的,能让我明白的例子。
现在的项目中也问题遇到OOM的错误,着实头疼。
其实主要是SoftReference不了解,看过之后还是理解不了它是怎么用的。
网上也搜过好多Java的四种引用方式,没能找到一个完整的,能让我明白的例子。
现在的项目中也问题遇到OOM的错误,着实头疼。
2013-04-23 01:10:49
回复 稚者杨力:[12楼]
呵呵,先给你讲个思路:不管是SoftReference、Weak Reference当中的哪一个,在内存解决的问题上真的很有帮助的,二者的区别看这里: http://johncookie.iteye.com/blog/1354394 我先讲个大体的思路吧,OOM一般是在连续decode的时候就出现的如果是ListView、GridView等包含多个子控件的控件中使用时,肯定是要用到缓存的,不然肯定报错,典型的处理方法就是在你第一次获取(decode的时候)到Bitmap的同时讲这个Bitmap以Map<Key,Value>的形式存入到SoftReference中,这个地方我给朋友你贴上一个类,你看下大体的思路
package net.oschina.app.common;
import java.io.File;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import net.oschina.app.AppException;
import net.oschina.app.api.ApiClient;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
/**
* 异步线程加载图片工具类
* 使用说明:
* BitmapManager bmpManager;
* bmpManager = new BitmapManager(BitmapFactory.decodeResource(context.getResources(), R.drawable.loading));
* bmpManager.loadBitmap(imageURL, imageView);
* @author liux (http://my.oschina.net/liux)
* @version 1.0
* @created 2012-6-25
*/
public class BitmapManager {
private static HashMap<String, SoftReference<Bitmap>> cache;
private static ExecutorService pool;
private static Map<ImageView, String> imageViews;
private Bitmap defaultBmp;
static {
cache = new HashMap<String, SoftReference<Bitmap>>();
pool = Executors.newFixedThreadPool(5); //固定线程池
imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
}
public BitmapManager(){}
public BitmapManager(Bitmap def) {
this.defaultBmp = def;
}
/**
* 设置默认图片
* @param bmp
*/
public void setDefaultBmp(Bitmap bmp) {
defaultBmp = bmp;
}
/**
* 加载图片
* @param url
* @param imageView
*/
public void loadBitmap(String url, ImageView imageView) {
loadBitmap(url, imageView, this.defaultBmp, 0, 0);
}
/**
* 加载图片-可设置加载失败后显示的默认图片
* @param url
* @param imageView
* @param defaultBmp
*/
public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp) {
loadBitmap(url, imageView, defaultBmp, 0, 0);
}
/**
* 加载图片-可指定显示图片的高宽
* @param url
* @param imageView
* @param width
* @param height
*/
public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp, int width, int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap != null) {
//显示缓存图片
imageView.setImageBitmap(bitmap);
} else {
//加载SD卡中的图片缓存
String filename = FileUtils.getFileName(url);
String filepath = imageView.getContext().getFilesDir() + File.separator + filename;
File file = new File(filepath);
if(file.exists()){
//显示SD卡中的图片缓存
Bitmap bmp = ImageUtils.getBitmap(imageView.getContext(), filename);
imageView.setImageBitmap(bmp);
}else{
//线程加载网络图片
imageView.setImageBitmap(defaultBmp);
queueJob(url, imageView, width, height);
}
}
}
/**
* 从缓存中获取图片
* @param url
*/
public Bitmap getBitmapFromCache(String url) {
Bitmap bitmap = null;
if (cache.containsKey(url)) {
bitmap = cache.get(url).get();
}
return bitmap;
}
/**
* 从网络中加载图片
* @param url
* @param imageView
* @param width
* @param height
*/
public void queueJob(final String url, final ImageView imageView, final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
try {
//向SD卡中写入图片缓存
ImageUtils.saveImage(imageView.getContext(), FileUtils.getFileName(url), (Bitmap) msg.obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
pool.execute(new Runnable() {
public void run() {
Message message = Message.obtain();
message.obj = downloadBitmap(url, width, height);
handler.sendMessage(message);
}
});
}
/**
* 下载图片-可指定显示图片的高宽
* @param url
* @param width
* @param height
*/
private Bitmap downloadBitmap(String url, int width, int height) {
Bitmap bitmap = null;
try {
//http加载图片
bitmap = ApiClient.getNetBitmap(url);
if(width > 0 && height > 0) {
//指定显示图片的高宽
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
}
//放入缓存
cache.put(url, new SoftReference<Bitmap>(bitmap));
} catch (AppException e) {
e.printStackTrace();
}
return bitmap;
}
}
呵呵,先给你讲个思路:不管是SoftReference、Weak Reference当中的哪一个,在内存解决的问题上真的很有帮助的,二者的区别看这里: http://johncookie.iteye.com/blog/1354394 我先讲个大体的思路吧,OOM一般是在连续decode的时候就出现的如果是ListView、GridView等包含多个子控件的控件中使用时,肯定是要用到缓存的,不然肯定报错,典型的处理方法就是在你第一次获取(decode的时候)到Bitmap的同时讲这个Bitmap以Map<Key,Value>的形式存入到SoftReference中,这个地方我给朋友你贴上一个类,你看下大体的思路
package net.oschina.app.common;
import java.io.File;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import net.oschina.app.AppException;
import net.oschina.app.api.ApiClient;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
/**
* 异步线程加载图片工具类
* 使用说明:
* BitmapManager bmpManager;
* bmpManager = new BitmapManager(BitmapFactory.decodeResource(context.getResources(), R.drawable.loading));
* bmpManager.loadBitmap(imageURL, imageView);
* @author liux (http://my.oschina.net/liux)
* @version 1.0
* @created 2012-6-25
*/
public class BitmapManager {
private static HashMap<String, SoftReference<Bitmap>> cache;
private static ExecutorService pool;
private static Map<ImageView, String> imageViews;
private Bitmap defaultBmp;
static {
cache = new HashMap<String, SoftReference<Bitmap>>();
pool = Executors.newFixedThreadPool(5); //固定线程池
imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
}
public BitmapManager(){}
public BitmapManager(Bitmap def) {
this.defaultBmp = def;
}
/**
* 设置默认图片
* @param bmp
*/
public void setDefaultBmp(Bitmap bmp) {
defaultBmp = bmp;
}
/**
* 加载图片
* @param url
* @param imageView
*/
public void loadBitmap(String url, ImageView imageView) {
loadBitmap(url, imageView, this.defaultBmp, 0, 0);
}
/**
* 加载图片-可设置加载失败后显示的默认图片
* @param url
* @param imageView
* @param defaultBmp
*/
public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp) {
loadBitmap(url, imageView, defaultBmp, 0, 0);
}
/**
* 加载图片-可指定显示图片的高宽
* @param url
* @param imageView
* @param width
* @param height
*/
public void loadBitmap(String url, ImageView imageView, Bitmap defaultBmp, int width, int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap != null) {
//显示缓存图片
imageView.setImageBitmap(bitmap);
} else {
//加载SD卡中的图片缓存
String filename = FileUtils.getFileName(url);
String filepath = imageView.getContext().getFilesDir() + File.separator + filename;
File file = new File(filepath);
if(file.exists()){
//显示SD卡中的图片缓存
Bitmap bmp = ImageUtils.getBitmap(imageView.getContext(), filename);
imageView.setImageBitmap(bmp);
}else{
//线程加载网络图片
imageView.setImageBitmap(defaultBmp);
queueJob(url, imageView, width, height);
}
}
}
/**
* 从缓存中获取图片
* @param url
*/
public Bitmap getBitmapFromCache(String url) {
Bitmap bitmap = null;
if (cache.containsKey(url)) {
bitmap = cache.get(url).get();
}
return bitmap;
}
/**
* 从网络中加载图片
* @param url
* @param imageView
* @param width
* @param height
*/
public void queueJob(final String url, final ImageView imageView, final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
try {
//向SD卡中写入图片缓存
ImageUtils.saveImage(imageView.getContext(), FileUtils.getFileName(url), (Bitmap) msg.obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
pool.execute(new Runnable() {
public void run() {
Message message = Message.obtain();
message.obj = downloadBitmap(url, width, height);
handler.sendMessage(message);
}
});
}
/**
* 下载图片-可指定显示图片的高宽
* @param url
* @param width
* @param height
*/
private Bitmap downloadBitmap(String url, int width, int height) {
Bitmap bitmap = null;
try {
//http加载图片
bitmap = ApiClient.getNetBitmap(url);
if(width > 0 && height > 0) {
//指定显示图片的高宽
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
}
//放入缓存
cache.put(url, new SoftReference<Bitmap>(bitmap));
} catch (AppException e) {
e.printStackTrace();
}
return bitmap;
}
}
0 0
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM)整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android的Bitmap内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结
- Android 内存溢出解决方案(OOM) 整理总结(转)
- Android 内存溢出解决方案(OOM) 整理总结
- 【天猫浏览型应用的CDN静态化架构演变】
- Android制作曲线、柱状图、饼形等图表——使用AChartEngine
- JNI 使用多线程回调java 方法
- 关于DBN fine-tunes使用BP多于up-down算法的一点看法
- 创建ApiDemo示例
- Android 内存溢出解决方案(OOM) 整理总结
- 项目测试管理杂谈
- 组播解惑
- infinispan配置
- 八大排序算法之二希尔排序(C语言)
- 提升ListView的运行效率
- Oracle db 11.2.0.4 linux 6.3下编译bbed
- Android 浏览器打开本地app
- POJ 2481 Cows
希望大家支持下!赞上一个,谢谢啦!
http://wws5201985.blog.51cto.com/216275/803871
本文收录至博客专题:《2012龙年薪途活动:秘籍大起底》
希望大家支持下!赞上一个,谢谢啦!