Question

I have used intent service to download a set video files, but while downloading some big size videos it is giving out of memory error in this part "byte[] responseBody = client.execute(getMethod, responseHandler);", I know byte array exceeds the size allotted heap for an app.

I am looking for some alternative solution to overcome this issue, please suggest me if you have some good fix.

    @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);
            }
        }
    }

Thanks in advance

Was it helpful?

Solution

The problem is this: You are using a ResponseHandler that simply reads the entire HTTP response into a byte array in memory. You don't have that much memory.

You need to get the underlying InputStream and loop, reading a reasonable amount of data from the stream then writing to your output file.

The InputStream is inside the HttpEntity which you get from the HttpResponse

You can either:

A) Write a custom ResponseHandler whose constructor you pass your File to and it does all the work.

or

B) Just call client.execute(getMethod). This will return the HttpResponse directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top