下载PDF文件时OutOfMemory

时间:2015-09-01 14:47:21

标签: android android-asynctask

在我正在制作的应用中,人们可以下载PDF文件。在我的Nexus 5上下载PDF时出现问题,但在HTC One X上出现Out of Memory错误。我怎么能避免这个?我正在使用的代码是:

@Override
protected Boolean doInBackground(String... params) {
    String fileUrl = params[0];
    mFileName = params[1];
    mFolder = new File(mContext.getFilesDir(), "pdfs");
    mFolder.mkdir();

    Random r = new Random();
    int i1 = r.nextInt(99 - 10) + 99;
    mFile = new File(mFolder, mFileName + "." + i1);
    try {
        mFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        System.gc();
        URL url = new URL(fileUrl);
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(mFile);
        int totalSize = urlConnection.getContentLength();

        byte[] buffer = new byte[MEGABYTE];
        int bufferLength = 0;
        long total = 0;
        while((bufferLength = inputStream.read(buffer))>0 ){
            total += bufferLength;

            int progress = (int)((total * 100) / totalSize);

            publishProgress(progress, (int)total, totalSize);
            fileOutputStream.write(buffer, 0, bufferLength);
        }
        fileOutputStream.close();

        return true;
    } catch (FileNotFoundException e) {
        mFile.delete();
        e.printStackTrace();
    } catch (MalformedURLException e) {
        mFile.delete();
        e.printStackTrace();
    } catch (IOException e) {
        mFile.delete();
        e.printStackTrace();
    }

    return false;
}


@Override
protected void onPostExecute(Boolean success) {
    if(mOnDownloadListener != null) {
        File to = new File(mFolder, mFileName);
        mFile.renameTo(to);

        mOnDownloadListener.onDownloaded(success);
    }
    super.onPostExecute(success);
}

0 个答案:

没有答案