2014-01-14 49 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