2014-01-14 48 views
0

我已經使用intent服務下載了一套視頻文件,但是在下載一些大尺寸的視頻時,它給出了這部分內存錯誤「byte [] responseBody = client.execute (getMethod,responseHandler);「,我知道字節數組超出了應用程序的大小分配堆。下載大視頻文件給出內存不足錯誤

我在尋找一些替代解決方案來解決這個問題,如果你有一些很好的修復方法,請給我建議。

@Override 
    public void onHandleIntent(Intent i) { 
     Log.d("gl", "onhandleintent"); 
     HttpGet getMethod = new HttpGet(i.getData().toString()); 
     int result = Activity.RESULT_CANCELED; 
     ad_id =i.getStringExtra("ad_id"); 

     try { 
      ResponseHandler<byte[]> responseHandler = new ByteArrayResponseHandler(); 
      byte[] responseBody = client.execute(getMethod, responseHandler); 
      Log.d("gl", "file name " + i.getData().getLastPathSegment()); 
      File output = new File(SharedPreferenceClass.readName(
        Downloader.this, "videoFolder", "itaxi-videos"), i 
        .getData().getLastPathSegment()); 

      if (output.exists()) { 
       output.delete(); 
      } 

      FileOutputStream fos = new FileOutputStream(output.getPath()); 

      fos.write(responseBody); 
      fos.close(); 
      result = Activity.RESULT_OK; 
     } catch (IOException e2) { 
      Log.e(getClass().getName(), "Exception in download", e2); 
      result = Activity.RESULT_CANCELED; 
     } 

     Bundle extras = i.getExtras(); 

     // sending back datas to the handle for further updations like db 
     if (extras != null) { 
      Messenger messenger = (Messenger) extras.get(EXTRA_MESSENGER); 
      Message msg = Message.obtain(); 
      msg.arg1 = result; 
      try { 
       Bundle bundle = new Bundle(); 
       bundle.putString("ad_id", ad_id); 
       msg.setData(bundle); 
       messenger.send(msg); 
      } catch (android.os.RemoteException e1) { 
       Log.w(getClass().getName(), "Exception sending message", e1); 
      } 
     } 
    } 

預先感謝

+3

在寫入磁盤之前,不要將整個響應存儲在內存中。問題解決了。 –

回答

1

問題是這樣的:您正在使用一個ResponseHandler,簡單地讀取整個HTTP響應到內存中的字節數組。你沒有那麼多的記憶。

您需要獲取底層InputStream和循環,從流中讀取合理數量的數據,然後寫入輸出文件。

InputStream是您從HttpResponse

得到HttpEntity內您可以:

A)編寫自定義ResponseHandler它的構造你通過File並它所有的工作。

B)只要打電話client.execute(getMethod)。這將直接返回HttpResponse