Home » Android » java – Opening file after download using BroadcastReceiver-Exceptionshub

java – Opening file after download using BroadcastReceiver-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I have encountered some issues getting this to work. The file downloads successfully however the pdf viewer on the device opens and the closes right away and an error is shown saying “file cannot be accessed check the location or network and try again” The only thing i can think of is the download is not completed when the pdf viewer is attempting to open the file. I am unsure on the placement of this line of code to register the broadcast receiver registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); as I believe this to be most of my problem possibly. I am very new to java and still trying to figure it out. The device is running android 10 API 29

MainActivity.java

    asw_view.setDownloadListener(new DownloadListener() {

        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        long downloadId;
        String file_Ext;
        String file_Type;

        private BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //Fetching the download id received with the broadcast
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                //Checking if the received broadcast is for our enqueued download by matching download id
                if (downloadId == id) {
                    Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();

                    Cursor c = dm.query(new DownloadManager.Query().setFilterById(downloadId));
                    if (c != null) {
                        c.moveToFirst();
                        try {
                            String fileUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                            File mFile = new File(Uri.parse(fileUri).getPath());
                            String fileName = mFile.getAbsolutePath();

                            MimeTypeMap mime = MimeTypeMap.getSingleton();
                            file_Ext = mFile.getName().substring(mFile.getName().lastIndexOf(".") + 1);
                            file_Type = mime.getMimeTypeFromExtension(file_Ext);

                            openFile(fileName, file_Type);
                        }catch (Exception e){
                            Log.e("error", "Could not open the downloaded file");
                        }
                    }
                }
            }
        };


        private void openFile(String fileToOpen, String file_Type){
            try {
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ fileToOpen);

                Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
                openFileIntent.setAction(Intent.ACTION_VIEW);
                openFileIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                Uri contentUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);
                openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                openFileIntent.setDataAndType(contentUri, file_Type);

                startActivity(openFileIntent);

            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "No pdf viewing application detected. File saved in download folder",Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {

            if (!check_permission(2)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, file_perm);
            } else {

                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                //Get the name of the file being downloaded from the url
                String DownloadFileName = url.substring(url.lastIndexOf("/") + 1);

                request.setMimeType(mimeType);
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription(getString(R.string.dl_downloading));
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
                //DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                assert dm != null;
                downloadId = dm.enqueue(request);

                Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2) + ": " + DownloadFileName, Toast.LENGTH_LONG).show();

                registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));


            }

        }
    });

The AndroidManifest.xml has both

<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:remove="android:maxSdkVersion" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Any help would be greatly appreciated

How to&Answers: