issues in writing files to sd card in android api 23(marshmallow)

后端 未结 3 1534
醉酒成梦
醉酒成梦 2020-12-22 12:59

i am getting error when i try to download this file in Api 23.it works well in version<23.I have seen similar questions like this,but none of the solution worked for me.

3条回答
  •  伪装坚强ぢ
    2020-12-22 13:20

    Please check below solution, hope it will work properly for you.

     public void startDownload(View v) 
     {
        int result = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
       if (result == PackageManager.PERMISSION_GRANTED){
    
           startDownloading();
    
       } else {
    
           requestForLocationPermission(); 
       }
     }
    
    
       private void requestForLocationPermission()
       {
    
          if (ActivityCompat.shouldShowRequestPermissionRationale(activity,Manifest.permission.WRITE_EXTERNAL_STORAGE))
          {
          } 
          else {
    
              ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_REQUEST_CODE);
          }
       }
    
      @Override
      public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) 
      {
          switch (requestCode) {
           case PERMISSION_REQUEST_CODE:
               if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
            { 
               startDownloading();
            } 
            break;
      }
    }
    
    
      public void startDownloading()
      {
          Uri uri=Uri.parse("http://oursite/pictures/image.jpg");
    
    
          Environment
      .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
      .mkdirs();
    
          lastDownload = mgr.enqueue(new DownloadManager.Request(uri)
                  .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
                                          DownloadManager.Request.NETWORK_MOBILE)
                  .setAllowedOverRoaming(false)
                  .setTitle("Pictures")
                  //.setDescription("Something useful. No, really.")
                  .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                                     "aadhar.jpg"));
    
          v.setEnabled(false);
          //findViewById(R.id.query).setEnabled(true);
        }
    

提交回复
热议问题