我如何从URL下载并保存设备存储“ Pdf文件”,然后单击RecyclerView?

时间:2019-08-09 19:30:42

标签: java android android-recyclerview

in detail click open Image

我的初学者使用git Hub帮助我

1 个答案:

答案 0 :(得分:1)

public void downloadFile(final String url, String fileName) {
    if (!fileName.endsWith(PDF_EXT))
        fileName = fileName.concat(PDF_EXT);
    downloadedFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
    PermissionManager permissionManager = PermissionManager.getInstance();
    final String finalFileName = fileName;
    permissionManager.requestPermission(getContext(),
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionListener() {
                @Override
                public void onPermissionGranted(Permission permission) {
                    if (downloadedFile.exists() && !isLoaded) {
                        hideLoadingView();
                        loadPdfView(downloadedFile);
                        isLoaded = true;
                    } else if (!downloadedFile.exists() && !isDownloading) {
                        isDownloading = true;
                        if (NetworkUtils.isMobileNetworkEnabled(getContext())) {
                            showDataWarning(url, finalFileName);
                        } else {
                            registerReceiver();
                            Intent intent = new Intent(getContext(), FileDownloadIntentService.class);
                            intent.putExtra(DOWNLOAD_FILE_URL, url);
                            intent.putExtra(DOWNLOAD_FILE_NAME, finalFileName);
                            getContext().startService(intent);
                        }
                    }
                }

                @Override
                public void onPermissionDenied(Permission permission) {
                    // handled by super
                }

                @Override
                public void onPermissionPermanentlyDenied(Permission permission) {
                    // no story
                }
            });
}




private static final int UPDATE_PERCENT_THRESHOLD = 1;
File downloadedFile;
private final String PDF_EXT = ".pdf";

public FileDownloadIntentService() {
    super("FileDownloadService started");
}

@Override
protected void onHandleIntent(Intent intent) {
    String fileUrl = intent.getStringExtra(DOWNLOAD_FILE_URL);
    String fileName = intent.getStringExtra(DOWNLOAD_FILE_NAME);
    if (!fileName.endsWith(PDF_EXT))
        fileName = fileName.concat(PDF_EXT);
    downloadedFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
    if (downloadedFile.exists())
        stopSelf();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL....).build();

    Call<ResponseBody> request = retrofit
            .create(FileDownloadClient.class)
            .downloadFileUrl(fileUrl);
    try {
        writeResponseBodyToDisk(request.execute().body());
    } catch (IOException e) {
        Timber.e(e.getMessage());
        if (downloadedFile.exists())
            downloadedFile.delete();
    }
}

private void writeResponseBodyToDisk(ResponseBody body) throws IOException {

    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {
        byte[] fileReader = new byte[4096];
        long fileSize = body.contentLength();
        inputStream = new BufferedInputStream(body.byteStream(), 4096);
        outputStream = new FileOutputStream(downloadedFile);
        int readBuffer;
        long fileSizeDownloadedInByte = 0;
        int fileDownloadedInPercentage = 0;

        while (true) {
            readBuffer = inputStream.read(fileReader);

            if (readBuffer == -1) {
                break;
            }

            fileSizeDownloadedInByte += readBuffer;
            int newfileDownloadedInPercentage = (int) ((fileSizeDownloadedInByte * 100) / fileSize);
            if (fileDownloadedInPercentage + UPDATE_PERCENT_THRESHOLD <= newfileDownloadedInPercentage) {
                fileDownloadedInPercentage = newfileDownloadedInPercentage;
            }

            outputStream.write(fileReader, 0, readBuffer);
        }
        sendUpdateUiIntent(100, fileSize);

        outputStream.flush();
    } catch (IOException e) {
        sendUpdateUiIntent(0, 0);
        if (downloadedFile.exists())
            downloadedFile.delete();
    } catch (Exception e) {
        Timber.e(e);
        if (downloadedFile.exists())
            downloadedFile.delete();
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }

        if (outputStream != null) {
            outputStream.close();
        }
    }
}

}

在上述方法中,您只需要传递从URL中提取并传递的url和标题。