Android中解决加载过多图片出现的OutOfMemoryOutOfMemory问题 .

首先呢,解决办法有好几种,降低图片的分辨率也不失一种办法,当然这里肯定不是这么用,也有直接更改虚拟机的内存的办法,

1. private final static floatTARGET_HEAP_UTILIZATION = 0.75f;

2. 在程序onCreate时就可以调用

3. VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);

这里是增强VM的内存回收效率。

 5:自定义我们的应用需要多大的内存,这个好暴力哇,强行设置最小内存大小,代码如下:

6. private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;

7. //设置最小heap内存为6MB大小

8. VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);

这是直接更改内存大小,游戏可以参考,我这也不是这么做的。

我这直接给出一个类,大家呢直接调用构造器

第一步ImageLoader il=new ImageLoader(getApplicationContext(), id);这里第一个参数是用来得到缓存目录的,第二个参数是加载图片前的默认图片。

第二步调用il.DisplayImage(url, imageView);第一个参数是图片的url,第二个参数是imagview。复制拷贝,直接能用。

  1. package com.example.doudizhu;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.lang.ref.SoftReference;  
  7. import java.util.Collections;  
  8. import java.util.HashMap;  
  9. import java.util.Map;  
  10. import java.util.Stack;  
  11. import java.util.WeakHashMap;  
  12. import android.app.Activity;  
  13. import android.content.Context;  
  14. import android.graphics.Bitmap;  
  15. import android.graphics.BitmapFactory;  
  16. import android.widget.ImageView;  
  17.   
  18.   
  19. public class ImageLoader {  
  20.   
  21.     MemoryCache memoryCache = new MemoryCache();  
  22.     FileCache fileCache;  
  23.     /**这是一个弱引用,map的弱引用,关键是同步的,线程安全的*/  
  24.     private Map<ImageView, String> imageViews = Collections  
  25.             .synchronizedMap(new WeakHashMap<ImageView, String>());  
  26.   
  27.     public ImageLoader(Context context,int id) {  
  28.         // Make the background thead low priority. This way it will not affect   
  29.         // the UI performance   
  30.         photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);  
  31.         stub_id=id;  
  32.         fileCache = new FileCache(context);  
  33.     }  
  34.     /**图片初始化的时显示的图片的id*/  
  35.     final int stub_id ;  
  36.     /** 
  37.      * 将最开始时的ImageView和url关联起来。因为最开始是空的所以显示的是初始化的图片 
  38.      * @param url 
  39.      * @param activity 
  40.      * @param imageView 
  41.      */  
  42.     public void DisplayImage(String url,  ImageView imageView) {  
  43.         imageViews.put(imageView, url);  
  44.         Bitmap bitmap = memoryCache.get(url);  
  45.         if (bitmap != null)  
  46.             imageView.setImageBitmap(bitmap);  
  47.         else {  
  48.             queuePhoto(url, imageView);  
  49.             imageView.setImageResource(stub_id);  
  50.         }  
  51.     }  
  52.     /** 
  53.      * 初始化图片,设置初始的图片 
  54.      * @param url 
  55.      * @param activity 
  56.      * @param imageView 
  57.      */  
  58.     private void queuePhoto(String url, ImageView imageView) {  
  59.         // This ImageView may be used for other images before. So there may be   
  60.         // some old tasks in the queue. We need to discard them.   
  61.         photosQueue.Clean(imageView);  
  62.         PhotoToLoad p = new PhotoToLoad(url, imageView);  
  63.         synchronized (photosQueue.photosToLoad) {  
  64.             photosQueue.photosToLoad.push(p);  
  65.             photosQueue.photosToLoad.notifyAll();  
  66.         }  
  67.   
  68.         // start thread if it's not started yet   
  69.         if (photoLoaderThread.getState() == Thread.State.NEW)  
  70.             photoLoaderThread.start();  
  71.     }  
  72.   
  73.     private Bitmap getBitmap(String url) {  
  74.         File f = fileCache.getFile(url);  
  75.         // from SD cache   
  76.         Bitmap b = decodeFile(f);  
  77.         if (b != null)  
  78.             return b;  
  79.   
  80.         // from web   
  81.         try {  
  82.             File myFile = new File(url);  
  83.             return decodeFile(myFile);  
  84.               
  85.         } catch (Exception ex) {  
  86.             ex.printStackTrace();  
  87.             return null;  
  88.         }  
  89.     }  
  90.   
  91.     // decodes image and scales it to reduce memory consumption   
  92.     private Bitmap decodeFile(File f) {  
  93.         try {  
  94.             // decode image size   
  95.             BitmapFactory.Options o = new BitmapFactory.Options();  
  96.             o.inJustDecodeBounds = true;  
  97.             BitmapFactory.decodeStream(new FileInputStream(f), null, o);  
  98.   
  99.             // Find the correct scale value. It should be the power of 2.   
  100.             final int REQUIRED_SIZE = 70;  
  101.             int width_tmp = o.outWidth, height_tmp = o.outHeight;  
  102.             int scale = 1;  
  103.             while (true) {  
  104.                 if (width_tmp / 2 < REQUIRED_SIZE  
  105.                         || height_tmp / 2 < REQUIRED_SIZE)  
  106.                     break;  
  107.                 width_tmp /= 2;  
  108.                 height_tmp /= 2;  
  109.                 scale *= 2;  
  110.             }  
  111.   
  112.             // decode with inSampleSize   
  113.             BitmapFactory.Options o2 = new BitmapFactory.Options();  
  114.             o2.inSampleSize = scale;  
  115.             return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);  
  116.         } catch (FileNotFoundException e) {  
  117.         }  
  118.         return null;  
  119.     }  
  120.   
  121.     // Task for the queue   
  122.     private class PhotoToLoad {  
  123.         public String url;  
  124.         public ImageView imageView;  
  125.   
  126.         public PhotoToLoad(String u, ImageView i) {  
  127.             url = u;  
  128.             imageView = i;  
  129.         }  
  130.     }  
  131.   
  132.     PhotosQueue photosQueue = new PhotosQueue();  
  133.   
  134.     public void stopThread() {  
  135.         photoLoaderThread.interrupt();  
  136.     }  
  137.   
  138.     // stores list of photos to download   
  139.     class PhotosQueue {  
  140.         private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();  
  141.         // removes all instances of this ImageView   
  142.         /*** 
  143.          * 移除掉堆栈当中的这个image 
  144.          * @param image 
  145.          */  
  146.         public void Clean(ImageView image) {  
  147.             for (int j = 0; j < photosToLoad.size();) {  
  148.                 if (photosToLoad.get(j).imageView == image)  
  149.                     photosToLoad.remove(j);  
  150.                 else  
  151.                     ++j;  
  152.             }  
  153.         }  
  154.     }  
  155.   
  156.     class PhotosLoader extends Thread {  
  157.         public void run() {  
  158.             try {  
  159.                 while (true) {  
  160.                     // thread waits until there are any images to load in the   
  161.                     // queue   
  162.                     if (photosQueue.photosToLoad.size() == 0)  
  163.                         synchronized (photosQueue.photosToLoad) {  
  164.                             photosQueue.photosToLoad.wait();  
  165.                         }  
  166.                     if (photosQueue.photosToLoad.size() != 0) {  
  167.                         PhotoToLoad photoToLoad;  
  168.                         synchronized (photosQueue.photosToLoad) {  
  169.                             photoToLoad = photosQueue.photosToLoad.pop();  
  170.                         }  
  171.                         Bitmap bmp = getBitmap(photoToLoad.url);  
  172.                         memoryCache.put(photoToLoad.url, bmp);  
  173.                         String tag = imageViews.get(photoToLoad.imageView);  
  174.                         if (tag != null && tag.equals(photoToLoad.url)) {  
  175.                             BitmapDisplayer bd = new BitmapDisplayer(bmp,  
  176.                                     photoToLoad.imageView);  
  177.                             Activity a = (Activity) photoToLoad.imageView  
  178.                                     .getContext();  
  179.                             a.runOnUiThread(bd);  
  180.                         }  
  181.                     }  
  182.                     if (Thread.interrupted())  
  183.                         break;  
  184.                 }  
  185.             } catch (InterruptedException e) {  
  186.                 // allow thread to exit   
  187.             }  
  188.         }  
  189.     }  
  190.   
  191.     PhotosLoader photoLoaderThread = new PhotosLoader();  
  192.   
  193.     // Used to display bitmap in the UI thread   
  194.     class BitmapDisplayer implements Runnable {  
  195.         Bitmap bitmap;  
  196.         ImageView imageView;  
  197.   
  198.         public BitmapDisplayer(Bitmap b, ImageView i) {  
  199.             bitmap = b;  
  200.             imageView = i;  
  201.         }  
  202.   
  203.         public void run() {  
  204.             if (bitmap != null)  
  205.                 imageView.setImageBitmap(bitmap);  
  206.             else  
  207.                 imageView.setImageResource(stub_id);  
  208.         }  
  209.     }  
  210.   
  211.     public void clearCache() {  
  212.         memoryCache.clear();  
  213.         fileCache.clear();  
  214.     }  
  215.     class FileCache {  
  216.           
  217.         private File cacheDir;  
  218.           
  219.         public FileCache(Context context){  
  220.             //Find the dir to save cached images   
  221.             if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))  
  222.                 cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");  
  223.             else  
  224.                 cacheDir=context.getCacheDir();  
  225.             if(!cacheDir.exists())  
  226.                 cacheDir.mkdirs();  
  227.         }  
  228.           
  229.         public File getFile(String url){  
  230.             //I identify images by hashcode. Not a perfect solution, good for the demo.   
  231.             String filename=String.valueOf(url.hashCode());  
  232.             File f = new File(cacheDir, filename);  
  233.             return f;  
  234.               
  235.         }  
  236.           
  237.         public void clear(){  
  238.             File[] files=cacheDir.listFiles();  
  239.             for(File f:files)  
  240.                 f.delete();  
  241.         }  
  242.   
  243.     }  
  244.     class MemoryCache {  
  245.         private HashMap<String, SoftReference<Bitmap>> cache=new HashMap<String, SoftReference<Bitmap>>();  
  246.           
  247.         public Bitmap get(String id){  
  248.             if(!cache.containsKey(id))  
  249.                 return null;  
  250.             SoftReference<Bitmap> ref=cache.get(id);  
  251.             return ref.get();  
  252.         }  
  253.           
  254.         public void put(String id, Bitmap bitmap){  
  255.             cache.put(id, new SoftReference<Bitmap>(bitmap));  
  256.         }  
  257.   
  258.         public void clear() {  
  259.             cache.clear();  
  260.         }  
  261.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值