Android 11 下载文件到下载文件夹不工作

Android 11 Download File to Download Folder doesn't work

目前我正在尝试使用 DownloadManager 下载文件,但这不起作用,下载开始但下载后下载文件夹中没有文件。

那是我的代码:

 private void downloadAddon() {
        try{
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
          //  request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            request.setTitle("download");
            request.setDescription("apk downloading");
            // request.setAllowedOverRoaming(false);
            request.setDestinationUri(Uri.fromFile(new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) , "mod.mcpack")));
            DownloadManager downloadManager =  (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            long downloadID = downloadManager.enqueue(request);

            //Just for testing
            if (downloadComplete(downloadID)) {
                Toast.makeText(this, "Download Status: Completed", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this, "Download Status: Error", Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){
            //Not required, there is no error that crashes the app
            Toast.makeText(this, "Error catched: " + e.getMessage(), Toast.LENGTH_SHORT).show();

        }

}
private boolean downloadComplete(long downloadId){
    DownloadManager dMgr = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    Cursor c= dMgr.query(new DownloadManager.Query().setFilterById(downloadId));

    if(c.moveToFirst()){
        int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));

        if(status == DownloadManager.STATUS_SUCCESSFUL){
            return true; //Download completed, celebrate
        }else{
            int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
            Log.d(getPackageName(), "Download not correct, status [" + status + "] reason [" + reason + "]");
            return false;
        }
    }
    return false;
}

日志显示:下载不正确,状态 [1] 原因 [0]

除了新的存储规则之外,自 Android11 以来有什么变化吗?

我在 Whosebug 上找到了解决方案(再也找不到 link)

 private boolean downloadTask(String url) throws Exception {
    if (!url.startsWith("http")) {
        return false;
    }
    String name = "temp.mcaddon";
    try {
        File file = new File(Environment.getExternalStorageDirectory(), "Download");
        if (!file.exists()) {
            //noinspection ResultOfMethodCallIgnored
            file.mkdirs();
        }
        File result = new File(file.getAbsolutePath() + File.separator + name);
        DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        request.setDestinationUri(Uri.fromFile(result));
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        if (downloadManager != null) {
            downloadManager.enqueue(request);
        }
        //mToast(mContext, "Starting download...");
        MediaScannerConnection.scanFile(DetailsActivity.this, new String[]{result.toString()}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                    }
                });
    } catch (Exception e) {
        Log.e(">>>>>", e.toString());
        //mToast(this, e.toString());
        return false;
    }
    return true;
}

这应该适用于 Android 11

使用此功能将文件保存在下载文件夹中:

private boolean downloadTask(String url , String name) throws Exception {
               try {
                   File file = new File(Environment.getExternalStorageDirectory(), "Download");
                   if (!file.exists()) {
                       //noinspection ResultOfMethodCallIgnored
                       file.mkdirs();
                   }
                   File result = new File(file.getAbsolutePath() + File.separator + name);
                   DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                   DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                   request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
                   request.setDestinationUri(Uri.fromFile(result));
                   request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                   request.setAllowedOverRoaming(false).setTitle(name);//for mp3 title
                   request.setDescription("Something useful. No, really.");
                   if (downloadManager != null) {
                       downloadManager.enqueue(request);
                   }
                   //mToast(mContext, "Starting download...");
                   MediaScannerConnection.scanFile(MainActivity.this, new String[]{result.toString()}, null,
                           new MediaScannerConnection.OnScanCompletedListener() {
                               public void onScanCompleted(String path, Uri uri) {
                                   Log.i("tag >>>>", "on Downlaod check it");
                                   

                               }
                           });
               } catch (Exception e) {
                   Log.i("tag >>>> ", e.toString());
                   return false;
               }
               return true;
           }

但在 Manifest 中添加一些行。

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

<application
        android:requestLegacyExternalStorage="true"
        android:usesCleartextTraffic="true"
  >

在 OnCreate 中添加这一行:

//check permission
if (Build.VERSION.SDK_INT >= 23) {
    Log.i("log ", "if in Build.VERSION.SDK_INT>=23");
    checkper(); //<-- this is a function
} else {
    Log.i("log ", " else else in Build.VERSION.SDK_INT>=23");
}

这是 checkper() 函数:

private final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
    private void checkper() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {


            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        } else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        } else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        } else if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        } else {

            Log.i("log", "else in checkper()");
            //your code
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED
                        && grantResults[2] == PackageManager.PERMISSION_GRANTED
                        && grantResults[3] == PackageManager.PERMISSION_GRANTED) {

                    Log.i("log", "if in onRequestPermissionsResult()");
                    //dar seri aval har do ra dasti ok kardim amad inja
                    //your code
                } else {

                    Log.i("log", "else in onRequestPermissionsResult()");
                    // yeki taiiid kardi
                }

            }


        }//switch
    }//onRequestPermissionsResult