2

So I have this method to write the response result from my server which is written to storage.

private boolean writeResponseBodyToDisk(ResponseBody body) {
        try {
            File filesDir = getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            assert filesDir != null;

            downloadedFile = new File(filesDir,
                    "file_name" + ".pdf");

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(downloadedFile);

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

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

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;
                }

                outputStream.flush();

                // This is how i call openPDF() method
                openPDF(Uri.fromFile(downloadedFile));

                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }

But how do you open this file immediately after successfully writing it to disk storage? I have tried to read the documentation entitled Access documents and other files from shared storage and Access app-specific files but the explanation does not lead to the information I need.

From what i read, I think it takes a differentiator to access storage from a different android version, like

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
     // only for gingerbread and newer versions
 }

I have tried this method but it doesn't work..

    private void openPDF(Uri uri) {
        try {
            Intent testIntent = new Intent("com.adobe.reader");
            testIntent.setType("application/pdf");
            testIntent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(uri);
            testIntent.setDataAndType(uri, "application/pdf");
            startActivity(testIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
Muhammad Faisal
  • 734
  • 10
  • 24

0 Answers0