4
    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

6
  • Do you have the required permissions? Apr 21, 2016 at 10:14
  • yes I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/> @camelCaseCoder Apr 21, 2016 at 10:15
  • Ok, is the file path correct? And are you testing this on Android 6? Apr 21, 2016 at 10:16
  • No, I am testing it on KitKat path is correct I can see the files Apr 21, 2016 at 10:17
  • Did you debug and see that the file location is absolutely correct and the file is actually present? Apr 21, 2016 at 10:20

3 Answers 3

2

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

1

Try using read permission:

android.permission.READ_EXTERNAL_STORAGE
0
0

Try like this...

protected void openFile(String fileName) {
    Intent install = new Intent(Intent.ACTION_VIEW);
    install.setDataAndType(Uri.fromFile(new File(fileName)),
            "MIME-TYPE");
    startActivity(install);
}
2
  • You can also see an example here github.com/commonsguy/cw-android/blob/master/Internet/Download/… Apr 21, 2016 at 10:22
  • I have create a dir final File folder = new File(Environment.getExternalStorageDirectory() + "Wonders"); boolean success = true; if (!folder.exists()) { success = folder.mkdir(); how to set the path request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, ******here**** , nameOfFile)@saurabh gupta Apr 21, 2016 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.