草庐IT

Android java.lang.OutOfMemoryError?

coder 2023-06-09 原文

04-25 08:19:10.111    2431-2603/com.example.francesco.guidedautorewithtabs E/art﹕ Throwing OutOfMemoryError "Failed to allocate a 4194316 byte allocation with 1983651 free bytes and 1937KB until OOM"
04-25 08:19:10.114    2431-2603/com.example.francesco.guidedautorewithtabs E/AndroidRuntime﹕ FATAL EXCEPTION: GLThread 285
Process: com.example.francesco.guidedautorewithtabs, PID: 2431
java.lang.OutOfMemoryError: Failed to allocate a 4194316 byte allocation with 1983651 free bytes and 1937KB until OOM
        at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
        at android.graphics.Bitmap.nativeCreate(Native Method)
        at android.graphics.Bitmap.createBitmap(Bitmap.java:817)
        at android.graphics.Bitmap.createBitmap(Bitmap.java:794)
        at android.graphics.Bitmap.createBitmap(Bitmap.java:761)
        at com.google.maps.api.android.lib6.gmm6.o.c.l.a(Unknown Source)
        at com.google.maps.api.android.lib6.gmm6.o.c.o.a(Unknown Source)
        at com.google.maps.api.android.lib6.gmm6.o.c.o.a(Unknown Source)
        at com.google.maps.api.android.lib6.gmm6.o.c.o.b(Unknown Source)
        at com.google.maps.api.android.lib6.gmm6.o.c.b.ak.a(Unknown Source)
        at com.google.maps.api.android.lib6.gmm6.o.c.b.as.a(Unknown Source)
        at com.google.maps.api.android.lib6.gmm6.o.x.a(Unknown Source)
        at com.google.maps.api.android.lib6.gmm6.o.l.a(Unknown Source)
        at com.google.maps.api.android.lib6.gmm6.o.l.b(Unknown Source)
        at com.google.maps.api.android.lib6.gmm6.o.cj.g(Unknown Source)
        at com.google.maps.api.android.lib6.gmm6.o.cj.run(Unknown Source)

在我的 Android 代码中,我有很多图像必须显示到不同的 fragment 中。其中一些存储在 assets 文件夹中,其他来自 http 请求。出于这个原因,我实现图像缓存是为了不违反 java.lang.OutOfMemoryError,但是这个错误似乎仍然存在。我该如何解决这个问题?下面是我的图像缓存实现。

图像加载器

public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
private Context context;

public ImageLoader(Context context){
    this.context=context;
    fileCache=new FileCache(context);
    executorService=Executors.newFixedThreadPool(5);
}

final int stub_id= R.drawable.no_image;
public void DisplayImage(String url, ImageView imageView)
{
    imageViews.put(imageView, url);
    Bitmap bitmap=memoryCache.get(url);
    if(bitmap!=null)
        imageView.setImageBitmap(bitmap);
    else
    {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }
}

private void queuePhoto(String url, ImageView imageView)
{
    PhotoToLoad p=new PhotoToLoad(url, imageView);
    executorService.submit(new PhotosLoader(p));
}

private Bitmap getBitmapFromAsset(String strName)
{
    AssetManager assetManager = context.getAssets();
    InputStream istr = null;
    try {
        istr = assetManager.open(strName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    return bitmap;
}

private Bitmap getBitmap(String url)
{
    File f=fileCache.getFile(url);

    //from SD cache
    Bitmap b = decodeFile(f);
    if(b!=null)
        return b;

    //from assets
    Bitmap bm = getBitmapFromAsset(url);

    if(bm!=null)
        return bm;

    //from web
    try {
        Bitmap bitmap=null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Throwable ex){
        ex.printStackTrace();
        if(ex instanceof OutOfMemoryError)
            memoryCache.clear();
        return null;
    }
}

//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
    try {
        //decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE=70;
        int width_tmp=o.outWidth, height_tmp=o.outHeight;
        int scale=1;
        while(true){
            if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                break;
            width_tmp/=2;
            height_tmp/=2;
            scale*=2;
        }

        //decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}
    return null;
}

//Task for the queue
private class PhotoToLoad
{
    public String url;
    public ImageView imageView;
    public PhotoToLoad(String u, ImageView i){
        url=u;
        imageView=i;
    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;
    PhotosLoader(PhotoToLoad photoToLoad){
        this.photoToLoad=photoToLoad;
    }

    @Override
    public void run() {
        if(imageViewReused(photoToLoad))
            return;
        Bitmap bmp=getBitmap(photoToLoad.url);
        memoryCache.put(photoToLoad.url, bmp);
        if(imageViewReused(photoToLoad))
            return;
        BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
        Activity a=(Activity)photoToLoad.imageView.getContext();
        a.runOnUiThread(bd);
    }
}

boolean imageViewReused(PhotoToLoad photoToLoad){
    String tag=imageViews.get(photoToLoad.imageView);
    if(tag==null || !tag.equals(photoToLoad.url))
        return true;
    return false;
}

//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
    Bitmap bitmap;
    PhotoToLoad photoToLoad;
    public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
    public void run()
    {
        if(imageViewReused(photoToLoad))
            return;
        if(bitmap!=null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(stub_id);
    }
}

public void clearCache() {
    memoryCache.clear();
    fileCache.clear();
}
}

文件缓存

public class FileCache {

private File cacheDir;

public FileCache(Context context){
    //Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"TTImages_cache");
    else
        cacheDir=context.getCacheDir();
    if(!cacheDir.exists())
        cacheDir.mkdirs();
}

public File getFile(String url){
    //I identify images by hashcode. Not a perfect solution, good for the demo.
    String filename=String.valueOf(url.hashCode());
    //Another possible solution (thanks to grantland)
    //String filename = URLEncoder.encode(url);
    File f = new File(cacheDir, filename);
    return f;

}

public void clear(){
    File[] files=cacheDir.listFiles();
    if(files==null)
        return;
    for(File f:files)
        f.delete();
}

}

内存缓存

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 25% of available heap size
    setLimit(Runtime.getRuntime().maxMemory()/4);
}

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){
        ex.printStackTrace();
        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() {
    try{
        //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
        cache.clear();
        size=0;
    }catch(NullPointerException ex){
        ex.printStackTrace();
    }
}

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

实用程序

public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
    final int buffer_size=1024;
    try
    {
        byte[] bytes=new byte[buffer_size];
        for(;;)
        {
            int count=is.read(bytes, 0, buffer_size);
            if(count==-1)
                break;
            os.write(bytes, 0, count);
        }
    }
    catch(Exception ex){}
}
}

最佳答案

试试这个可能对你有帮助 在你的 list 文件中添加这个标签。

<application android:largeHeap="true">
</application>

它将为您的应用分配大堆

关于Android java.lang.OutOfMemoryError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29861929/

有关Android java.lang.OutOfMemoryError?的更多相关文章

  1. java - 为什么 ruby​​ modulo 与 java/other lang 不同? - 2

    我基本上来自Java背景并且努力理解Ruby中的模运算。(5%3)(-5%3)(5%-3)(-5%-3)Java中的上述操作产生,2个-22个-2但在Ruby中,相同的表达式会产生21个-1-2.Ruby在逻辑上有多擅长这个?模块操作在Ruby中是如何实现的?如果将同一个操作定义为一个web服务,两个服务如何匹配逻辑。 最佳答案 在Java中,模运算的结果与被除数的符号相同。在Ruby中,它与除数的符号相同。remainder()在Ruby中与被除数的符号相同。您可能还想引用modulooperation.

  2. Ruby 看不到 NLS_LANG 环境变量 - 2

    我在CentOS上运行一个ruby​​脚本,并通过rvm(1.9.3)安装了ruby​​。我已经在.bash_profile中设置了NLS_LANG变量。[app@boxstasis]$echo$NLS_LANGen_US.UTF-8[app@boxstasis]$whichruby~/.rvm/rubies/ruby-1.9.3-p194/bin/ruby然而,当试图通过ruby​​(oci8驱动程序所做的)访问它时,它找不到它:1.9.3-p194:001>ENV['NLS_LANG']=>nil访问其他变量似乎有效:1.9.3-p194:004>ENV['USER']=>"app

  3. ruby - 在 JRuby 中,如何确定导致 java.lang.ThreadDeath 的原因? - 2

    在为一些与JRuby中的临时文件交互的代码运行单元测试时,我有时会得到以下信息:Exception:java.lang.ThreadDeaththrownfromtheUncaughtExceptionHandlerinthread"Thread-6395"它似乎没有引起任何问题,但这是怎么回事,我如何确定它发生在哪里?我尝试打开-d,但这并没有给我异常的堆栈跟踪。 最佳答案 FWIW:这可能与http://jira.codehaus.org/browse/JRUBY-7074有关.我偶尔会在不使用反引号但调用系统的JRuby程序中

  4. 报java.lang.AssertionError错误: - 2

    1.在使用Assert.assertEquals时报一个错误:2.首先,我们的明白Assert的用法:assert​如果为true,则程序继续执行。​如果为false,则程序抛出AssertionError,并终止执行assert:​如果为true,则程序继续执行。​如果为false,则程序抛出java.lang.AssertionError,并输出。ctrl点进Assert.assertEquals发现进行的是判断两个Object类型的值,他们两个比较的是引用地址是否相等,并没有对内容进行比较:如果两者一致,程序继续往下运行.如果两者不一致,中断测试方法,抛出异常信息AssertionFai

  5. javascript - 如何动态设置 HTML lang 属性? - 2

    如何在Web应用程序中动态设置HTML的“lang”属性?我尝试使用jQuery如下插入“lang”属性:$(document).ready(function(){$("html").attr("lang",language);//'language'valueisretrievedfromacookie});使用控制台/警报,'lang'属性看起来已按预期设置。但是,如果您看到生成的源代码(查看源代码),则根本没有设置“lang”。要求是屏幕阅读器必须能够动态识别语言。如果有任何其他解决方案可以使屏幕阅读器动态识别语言,那就太好了。感谢大家在线发表评论!

  6. javascript - Javascript 中的 Lang.Class - 2

    我正在尝试使用GJS(GnomeJavascript)开发GnomeShell扩展,但是,我遇到了Lang库(我认为它是一个库,如果我不正确的话)。但是我在网上找不到任何关于它的资源。在代码中它看起来像这样:constLang=imports.lang;constObjectA=newLang.Class({...});我在哪里可以找到有关它的文档?它是Gnome库吗?Mozilla库? 最佳答案 它是gjs的内置模块--参见modules/lang.js.它包括两个主要部分:bind()(使“this”指向闭包中的逻辑对象的助手)

  7. javascript - 未捕获的类型错误 : lang is not a function - 2

    这个问题在这里已经有了答案:JSfunctionnamed`animate`doesn'tworkinChrome,butworksinIE(3个答案)关闭6年前。在我的HTML中,我在script标签中定义了lang函数并添加了“TestFire!”单击时必须调用lang的按钮:TestingFunctionsfunctionlang(){alert("Hello,World!It'sJavaScriptthistime");}但是,如果我点击按钮,我会得到这个错误:UncaughtTypeError:langisnotafunction但是,如果我将函数名称从lang更改为任何其他

  8. go - 在 go lang 中对字符串进行排序 - 2

    如何在golang中对4.3.4、4.3.30等字符串进行排序。golang中有一个名为“sort”的方法?问题是使用此方法4.3.30在4.3.4之前打印。我希望4.3.30在4.3.4之后打印。这种排序的逻辑是什么?注意-我只需要一个逻辑天气,它将在go或java中。提前致谢。供您引用,go中的“排序”程序:packagemainimport"sort"import"fmt"typeByLength[]stringfunc(sByLength)Len()int{returnlen(s)}func(sByLength)Swap(i,jint){s[i],s[j]=s[j],s[i]}

  9. json - 我如何在 Go Lang 中使用多个元素对 JSON 进行编码 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭5年前。Improvethisquestion我需要咨询或示例代码,了解如何向客户发送JSON中的多个元素。谢谢!我需要下一个JSON结构:{{"id":123,"first_name":"Demo","last_name":"User","time":"2017-07-03T16:36:41.4101847Z","count":1,"payout":"839`"},{"id":124,"first_name":"Demo","last_na

  10. git - 我正在尝试安装 Go lang 包,但它给出了这样的错误::错误:以下未跟踪的工作树文件将被 merge 覆盖 - 2

    我的Gointellisense自动完成功能不工作,我正在尝试安装gocode和gopkg但它失败了,并给出了类似git的错误:::cd/home/poojat/go/src/golang.org/x/tools;gitpull--ff-onlyerror:Yourlocalchangestothefollowingfileswouldbeoverwrittenbymerge:CONTRIBUTING.mdREADMEblog/blog.gocmd/bundle/main.gocmd/callgraph/main.gocmd/callgraph/main_test.gocmd/call

随机推荐