How to use Android DownloadManager?

前端 未结 2 579
闹比i
闹比i 2020-12-24 15:56

I want to download a file to SDCard with Android DownloadManager class:

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


        
相关标签:
2条回答
  • 2020-12-24 16:03

    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() gives me /mnt/sdcard/downloads

    And I'm able to use the downloaded file in onReceive (ACTION_DOWNLOAD_COMPLETE)

    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
    Query query = new Query();
    query.setFilterById(downloadId);
    Cursor cur = dm.query(query);
    
    if (cur.moveToFirst()) {
        int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
        if (DownloadManager.STATUS_SUCCESSFUL == cur.getInt(columnIndex)) {
            String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
    
            File mFile = new File(Uri.parse(uriString).getPath());
            ....
    
        } else {
            Toast.makeText(c, R.string.fail, Toast.LENGTH_SHORT).show();
        }
    }
    
    0 讨论(0)
  • 2020-12-24 16:14

    You can retrieve file path from localUri like this:

    public static String getFilePathFromUri(Context c, Uri uri) {
        String filePath = null;
        if ("content".equals(uri.getScheme())) {
            String[] filePathColumn = { MediaColumns.DATA };
            ContentResolver contentResolver = c.getContentResolver();
    
            Cursor cursor = contentResolver.query(uri, filePathColumn, null,
                    null, null);
    
            cursor.moveToFirst();
    
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
            cursor.close();
        } else if ("file".equals(uri.getScheme())) {
            filePath = new File(uri.getPath()).getAbsolutePath();
        }
        return filePath;
    }
    
    0 讨论(0)
提交回复
热议问题