2015-02-08 76 views
0

我正在从一个应用程序使用AsyncTask + for循环加载大量的SD卡图像,我测试了我的Galaxy Nexus上的应用程序,该应用程序工作完美,但它会崩溃,如果我使用超过33循环Android AsyncTask Overload

我的问题是:是否有使用AsyncTask ???的限制,,,在我的代码中是否有任何错误导致33循环崩溃?

请大家帮忙,这里是我的代码:

ImageView iv; 
TextView tv; 
String picsDir; 
int picsAmount; 
String [] list;File dir; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //images folder 
    picsDir = Environment.getExternalStorageDirectory().toString()+"/aFolder"; 

    // total images 
    picsAmount = 70; 

    iv = (ImageView)findViewById(R.id.iv); 
    tv = (TextView)findViewById(R.id.tv); 

    list = new String [picsAmount]; 
    dir = new File (picsDir);   

    // String array of my images names 
    list = dir.list(); 

    new loadingImgs().execute(list); 
} 

class loadingImgs extends AsyncTask<String, Void, Drawable>{ 

    @Override 
    protected void onPreExecute() { 
     // nothing 
     super.onPreExecute(); 
    } 

    @Override 
    protected Drawable doInBackground(String... params) { 

     String dir1 = Environment.getExternalStorageDirectory().toString()+"/aFolder"; 

     String[] theList = params; 
     Bitmap[] bmp = new Bitmap[picsAmount]; 
     Drawable[] drw = new Drawable[picsAmount]; 

     tv.setText("dir1="+dir1+" found= "+picsAmount);    
     File dir = new File(dir1);   



     for (int i = 0; i < picsAmount; i++){ 
      bmp[i] = BitmapFactory.decodeFile(dir+"/"+theList[i]); 
      drw[i] = new BitmapDrawable(getResources(), bmp[i]);   
     }   

     return drw[0]; 
    } 

    protected void onPostExecute(Drawable result) { 

     // set drw[0] as iv image 
     iv.setImageDrawable(result); 


     }; 

} 

}

+0

您能否具体说明“崩溃”是什么意思?你可以发布你的堆栈跟踪吗? – 2015-02-08 19:37:26

+0

它与内存溢出异常崩溃? – Leonidos 2015-02-08 19:41:46

+0

是的,除非这些图像很小,否则可能是内存不足。没有真正的解决方案,除了一次不加载多个图像。你是否真的需要在屏幕上同时使用它们?如果没有的话,一个LRUCache可以保存屏幕上的内容并按需加载,效果会更好。 – 2015-02-08 19:43:16

回答

0

你崩溃时,你得到什么样的错误?

它是“OutOfMemoryException”吗?

当然是有没有循环的数量硬限制,你可以使用:)

你只是在堆上分配太多的空间,可能比你的设备可以为每个应用程序处理更多。

ActivityManager上使用getMemoryClass()可获取有关您的环境细节的更多信息。

+0

会,你r右,我有​​大约600mb的内存,但是图像非常小,它们的总大小约为3mb,它们中的每一个都在30kb左右,如何避免此错误,同时使用for循环进行快速输入 – user3843006 2015-02-08 22:51:04

+0

总大小你提到的可能是压缩的PNG或JPEG图像。位图是未压缩的,每个像素在内存中占用四个字节。我猜你的图像是720×1200,这使得每个图像3.3 MiB。 – StenSoft 2015-02-09 01:02:24

+0

@ user3843006你肯定没有接近600mb的内存可用。现在大多数手机的每个应用程序/ Linux进程都有24MB的限制。检查ActivityManager文档。 – joakim 2015-02-09 01:31:52

0

Bitmap s use huge amounts of memory。你应该避免同时在内存中拥有如此多的内存。

+0

我该怎么做,我想加载超过100个图像使用for循环,是否有任何为什么要避免这个错误? – user3843006 2015-02-08 22:46:59

+0

为什么在内存中同时需要100张图像?使用'for'循环,并在每次迭代中加载位图,从中创建drawable并回收位图。 – StenSoft 2015-02-09 00:55:28