Android中的AsyncTask和Out Of Memory问题

时间:2012-05-07 08:59:10

标签: android asynchronous bitmap android-asynctask

根据我的应用程序,我首先将所有图像从我的资源复制到内部存储器,然后在图像幻灯片上向左或向右移动我从内存中获取带有索引的图像并将其显示在那里。而我正在使用AsynTask。显示大约10张图像后,应用程序进入黑屏,日志猫说“此过程的外部分配太大”。根据我在这里阅读的内容,我认为问题是关于AsyncTask,我无法释放已经用于这些任务的内存。 我有三个不同的活动,用于将图像显示为图库,每个活动都使用asyncTask来显示图像。

以下是我的一些代码,任何帮助都将是感谢,请提前致谢。 这是我用于根据滑动图像执行图像下载的活动。

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;
}

}

3 个答案:

答案 0 :(得分:0)

它与AsyncTask无关。您将不得不更有效地使用位图。 搜索位图OOM; 在here

中对您下载的images.as进行一些抽样

还搜索Android SoftReference。

答案 1 :(得分:0)

尝试使用此链接来管理位图缓​​存,有许多解决方案可以防止outofMemory异常。 http://developer.android.com/training/displaying-bitmaps/index.html

答案 2 :(得分:0)

我找到了一种方法,现在它运行得很好,而不是使用文件流和位图获取图像现在我通过使用下面的代码设置drawable来实现。至于从互联网下载的图像,任何想做的人类似的东西,只需下载图像并将其保存在内部存储器或外部存储器中,然后只需给出图像的路径。

ImageView imageView = (ImageView) findViewById(R.id.image); 
File filePath = getFileStreamPath(fileName);
imageView.setImageDrawable(Drawable.createFromPath(filePath));