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


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


    asw_view.setDownloadListener(new DownloadListener() {

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

        private BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {
            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) {
                        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.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);

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


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

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

                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                request.addRequestHeader("User-Agent", userAgent);
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                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

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

Any help would be greatly appreciated

How to&Answers: