title: Can't use Storage Access Framework in my app
body: <p>I created an app a few years ago which had it's own file explorer and does so many processes on selected files. recently I wanted to add ability to write to external storages like SD Cards and Hard drives connected through OTG.
  The problem is I can't rewrite the whole project based on DocumentFile structure since it's a very big project and it would take forever for me to update. So I needed to somehow convert the old File methods in a few lines and be done with it. this is what I've added so far :</p>
  
  <pre><code>private void getPersistentPermission() {
      Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
      intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
      startActivityForResult(intent, reqcode_storage);
  }
  </code></pre>
  
  <p>and :</p>
  
  <pre><code>@Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (resultCode == RESULT_OK) {
          if (requestCode == reqcode_storage) {
              Uri uri = data.getData();
              if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.KITKAT) {
                  final int perm_flag = Intent.FLAG_GRANT_READ_URI_PERMISSION |
                          Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
                  grantUriPermission(getPackageName(), uri, perm_flag);
                  getContentResolver().takePersistableUriPermission(uri, perm_flag);
              }
          }
      } else {
          Log.d(tag, "something`s wrong !");
      }
  }
  </code></pre>
  
  <p>then I try to do something like this :</p>
  
  <pre><code>try {
      DocumentFile dfile = DocumentFile.fromFile(file);
      OutputStream os = getContentResolver().openOutputStream(dfile.getUri());
      os.write(some_string.getBytes());
  } catch (Exception e) {
      Log.e(tag, e.toString());
  } finally {
      try {
          os.close();
      } catch (Exception ignored) {}
  }
  </code></pre>
  
  <p>I get the "file" using implemented file explorer inside my app. it works for internal storage.
  I read so many threads about SAF but somehow I can't get it to work. it always shows this error :</p>
  
  <pre><code>java.io.FileNotFoundException: Permission denied
  </code></pre>
  
  <p>Can anyone tell me what am I missing here ?
  thanks in advance.</p>