Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After download how to open downloaded file?

    DownloadManager.Request request = new DownloadManager.Request(uri);
      request.setDestinationInExternalPublicDir(Environment.
                        DIRECTORY_DOWNLOADS, nameOfFile)

To open it

       File file = new File(Environment.
                    DIRECTORY_DOWNLOADS, nameOfFile);
            MimeTypeMap map = MimeTypeMap.getSingleton();
            String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
            String type = map.getMimeTypeFromExtension(ext);

But I am getting an error message that file cannot be accessed.Check the location

like image 433
Agniveer Kranti Avatar asked Oct 30 '25 09:10

Agniveer Kranti


1 Answers

Here is a working solution. Note: Dont use DownloadManager.COLUMN_LOCAL_FILENAME as it is deprecated in API 24. Use DownloadManager.COLUMN_LOCAL_URI instead.

  1. Create fields downlaod manager and a long variable to hold the download id.

    DownloadManager dm;
    long downloadId;
    String  pendingDownloadUrl = url;
    fial int storagePermissionRequestCode = 101;
    
  2. Create download manager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

  3. register the broadcast receiver for download complete

     BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            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();
                    openFile(fileName);
                }catch (Exception e){
                    Log.e("error", "Could not open the downloaded file");
                }
            }
        }
    };      
    

//register boradcast for download complete

registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
  1. Start the download

Start the download

private  void onDownloadStart(String url) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    downloadFile(url);
} else {
    pendingDownloadUrl = url;
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, storagePermissionRequestCode);
} } 

//Download file using download manager

private void downlaodFile(String url){
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    String filename = URLUtil.guessFileName(url, null, null);
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename);
    downloadId = dm.enqueue(request);//save download id for later reference }

//Permission status

@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if(requestCode == storagePermissionRequestCode){
        boolean canDownload = true;
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                canDownload = false;
                break;
            }
        }
        if(canDownload){
            downlaodFile(pendingDownloadUrl);
        }
    }        }
  1. Open the downloaded file

    private void openFile(String file) {
    try {
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.fromFile(new File(file)), "application/pdf");//this is for pdf file. Use appropreate mime type
        startActivity(i);
    } catch (Exception e) {           
        Toast.makeText(this,"No pdf viewing application detected. File saved in download folder",Toast.LENGTH_SHORT).show();
    }
    }
  2. Now try download your file by calling downladFile(String url); method

like image 177
subair_a Avatar answered Nov 02 '25 00:11

subair_a



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!