2012-11-15 80 views
-1

下載多個圖像(> 2MB每個)這是我的代碼,我得到一個內存不足的異常,同時下載多個圖像。我經歷了一個重複的問題,但沒有找到合適的答覆。Android的內存溢出異常,而從服務器

try { 
    HttpGet httpRequest = new HttpGet("http://staging.xyz.com/db/demo_img/abc.png"); 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); 
    HttpEntity entity = response.getEntity(); 
    BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity); 
    InputStream is = bufferedHttpEntity.getContent(); 
    //Drawable d = Drawable.createFromStream(is, ""); 
    //or bitmap 
    //photos = BitmapFactory.decodeStream(is); 
    BitmapFactory.Options o = new BitmapFactory.Options(); 
    o.inJustDecodeBounds = true; 
    BitmapFactory.decodeStream(is,null,o); 
    //The new size we want to scale to 
    final int REQUIRED_SIZE=70; 
    //Find the correct scale value. It should be the power of 2. 
    int scale=1; 
    while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE) 
    scale*=2; 
    //Decode with inSampleSize 
    BitmapFactory.Options o2 = new BitmapFactory.Options(); 
    o2.inSampleSize=scale; 
    Bitmap photos= BitmapFactory.decodeStream(is, null, o2); 

} catch (MalformedURLException e) { 
    System.out.println("photo error1111"); 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (IOException e) { 
    System.out.println("photo error1111"); 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

回答

2

我注意到你沒有回收位圖。那可能是你問題的根源嗎?

+0

我一次下載多張圖片,那麼在將它們設置爲圖像瀏覽之前,我如何回收這些位圖? – ParijatDev

+0

你有多個線程 - 每一個下載的圖像,縮放,然後使用http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)的設定呢? – wojciii

+0

號我有一個單一的AsyncTask內對此我下載圖像。出現錯誤----- 「應用程序可能在其主線程上做了太多工作。」 – ParijatDev

0
ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
     photos.compress(Bitmap.CompressFormat.JPEG, 40, bytes); 

只需添加這將節省內存烏爾

或者乾脆試試這個:

BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inSampleSize=2;        CameraAndFolderActivity.myBitmap = BitmapFactory.decodeFile(info.aImagePath, options); 
+0

字節表示另一個輸出流。這將如何服務於我的目的。你可以只給你自己的版本的巢幾行代碼? – ParijatDev

-1

使用垃圾收集器..

System.gc(); 
+0

不會滿足我的目的... – ParijatDev