0

根据我的应用程序,首先我将所有图像从我的资源复制到内部存储器,然后在图像向左或向右滑动上,我从内存中获取图像及其索引并将其显示在那里。我正在用 AsynTask 做这件事。在显示大约 10 张图像后,应用程序进入黑屏,并且 log cat 说“外部分配对于这个过程来说太大了”。根据我在这里阅读的内容,我认为问题出在 AsyncTask 上,我无法释放已用于这些任务的内存。我有三个不同的活动,用于将图像显示为图库,并且每个活动都使用 asyncTask 来显示图像。

下面是我的一些代码,任何帮助将不胜感激,在此先感谢。这是我用来根据滑动图像执行图像下载器的 Activity。

lid1 = new LocalImageDownloader(imageSwitcher, myContext, path, nameList.get(curIndex) );
            lid1.execute();

            imageSwitcher.setOnTouchListener(new OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {

                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        downX = (int) event.getX(); 
                        Log.i("event.getX()", " downX " + downX);
                        return true;
                    } 

                    else if (event.getAction() == MotionEvent.ACTION_UP) {
                        upX = (int) event.getX(); 
                        Log.i("event.getX()", " upX " + downX);
                        if (upX - downX > 100) {

                            //curIndex  current image index in array viewed by user
                            curIndex--;
                            if (curIndex < 0) {
                                curIndex = imageList.size()-1;
                            }

                            imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(Activities.this,R.anim.slide_in_left));
                            imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(Activities.this,R.anim.slide_out_right));

                            lid1.cancel(true);
                            lid1 = new LocalImageDownloader(imageSwitcher, myContext, path, nameList.get(curIndex) );
                            lid1.execute();
                        }

                        else if (downX - upX > -100) {

                            curIndex++;
                            if (curIndex == imageList.size() ) {
                                curIndex = 0;
                            }

                            imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(Activities.this,R.anim.slide_in_right));
                            imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(Activities.this,R.anim.slide_out_left));

                            lid1.cancel(true);
                            lid1 = new LocalImageDownloader(imageSwitcher, myContext, path, nameList.get(curIndex) );
                            lid1.execute();
                        }
                        return true;
                    }
                    return false;
                }
            });

这是我的 AsyncTask 从内存中获取图像,

public class LocalImageDownloader extends AsyncTask<String, Void, Bitmap> {

String url;
Drawable d;
Context myContext;

String path;
String fileName;

ProgressDialog dialog;
int REQUIRED_SIZE=600;

private final WeakReference<ImageSwitcher> imageViewReference;

public LocalImageDownloader(ImageSwitcher imageSwitcher,Context myContext, String path, String fileName) {
    this.myContext = myContext;
    this.path = path;
    this.fileName = fileName;
    imageViewReference = new WeakReference<ImageSwitcher>(imageSwitcher);
}

@Override
protected Bitmap doInBackground(String... urls) {
    publishProgress();
    return null;
}

@Override
protected void onPreExecute() {
    dialog = ProgressDialog.show(myContext, "", "Loading Images...", true);
    super.onPreExecute();
}

@Override
protected void onPostExecute(Bitmap result) {

    try {
        if (imageViewReference != null) {
            ImageSwitcher imageSwitcher = imageViewReference.get();
            if (imageSwitcher != null) {
                imageSwitcher.setImageDrawable(getLocalImage());
            }
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    dialog.dismiss();
}

public Drawable getLocalImage() throws IOException {

    File file = new File(path,fileName);

    //Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(new FileInputStream(file),null,o);

    //The new size we want to scale to

    //Find the correct scale value. It should be the power of 2.
    int scale=1;
    while(o.outWidth/scale/2>=this.REQUIRED_SIZE && o.outHeight/scale/2>=this.REQUIRED_SIZE)
        scale*=2;

    //Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize=scale;
    o.inJustDecodeBounds = false;

    return new BitmapDrawable(BitmapFactory.decodeStream(new FileInputStream(file), null, o2));
}

}

编辑: 我已经应用了一些方法来更有效地使用位图,现在我将它们推送到内存中,但我仍然遇到几乎相同的错误。一些图像存储在内存中后,对于一些图像,我会黑屏并出现相同的错误。“此过程的外部分配太大。” 知道怎么做吗?

下面是内存缓存代码,我将 MemoryCache 对象作为参数发送到 AsyncTask。

public class MemoryCache {

private static final String TAG = "MemoryCache";
private Map<String, Bitmap> cache=Collections.synchronizedMap(
        new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
private long size=0;//current allocated size
private long limit=1000000;//max memory in bytes

public MemoryCache(){
    //use 50% of available heap size
    setLimit(Runtime.getRuntime().maxMemory()/2);
}

public void setLimit(long new_limit){
    limit=new_limit;
    Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
}

public Bitmap get(String id){
    try{
        if(!cache.containsKey(id))
            return null;
        //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
        return cache.get(id);
    }catch(NullPointerException ex){
        return null;
    }
}

public void put(String id, Bitmap bitmap){
    try{
        if(cache.containsKey(id))
            size-=getSizeInBytes(cache.get(id));
        cache.put(id, bitmap);
        size+=getSizeInBytes(bitmap);
        checkSize();
    }catch(Throwable th){
        th.printStackTrace();
    }
}

private void checkSize() {
    Log.i(TAG, "cache size="+size+" length="+cache.size());
    if(size>limit){
        Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated  
        while(iter.hasNext()){
            Entry<String, Bitmap> entry=iter.next();
            size-=getSizeInBytes(entry.getValue());
            iter.remove();
            if(size<=limit)
                break;
        }
        Log.i(TAG, "Clean cache. New size "+cache.size());
    }
}

public void clear() {
    cache.clear();
}

long getSizeInBytes(Bitmap bitmap) {
    if(bitmap==null)
        return 0;
    return bitmap.getRowBytes() * bitmap.getHeight();
}

public boolean contains(String key) {

    if(cache.containsKey(key)) {
        return true;
    }

    return false;
}

}

4

3 回答 3

0

它与 AsyncTask 无关。您将不得不更有效地使用位图。搜索位图OOM;对您下载的图像进行一些采样。如这里

同时搜索 Android SoftReference。

于 2012-05-07T09:12:16.497 回答
0

试试这个链接来管理你的位图缓存,有很多解决方案可以防止 outofMemory 异常。http://developer.android.com/training/displaying-bitmaps/index.html

于 2012-05-07T09:55:22.843 回答
0

我找到了一种方法,现在效果很好,现在我不是通过文件流和位图获取图像,而是通过使用下面的代码设置可绘制对象来做到这一点。至于从互联网下载的图像,任何想做类似事情的人,只需下载图像并将其保存在内部存储器或外部存储器中,然后只需提供图像的路径即可。

ImageView imageView = (ImageView) findViewById(R.id.image); 
File filePath = getFileStreamPath(fileName);
imageView.setImageDrawable(Drawable.createFromPath(filePath));
于 2012-05-09T15:21:12.400 回答