2015-02-08 78 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