【问题标题】:Downloading big video file giving out of memory error下载大视频文件时出现内存不足错误
【发布时间】:2014-01-14 15:33:11
【问题描述】:

我使用 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);
            }
        }
    }

提前致谢

【问题讨论】:

  • 在写入磁盘之前不要将整个响应存储在内存中。问题解决了。

标签: android download out-of-memory intentservice


【解决方案1】:

问题是这样的:您正在使用ResponseHandler,它只是将整个 HTTP 响应读取到内存中的字节数组中。你没有那么多内存。

您需要获取底层InputStream 并循环,从流中读取合理数量的数据,然后写入您的输出文件。

InputStream 在您从HttpResponse 获得的HttpEntity

您可以:

A) 编写一个自定义的ResponseHandler,将File 传递给它的构造函数,它会完成所有工作。

B) 只需致电client.execute(getMethod)。这将直接返回HttpResponse

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多