Ejemplo n.º 1
0
 @Override
 public DocumentFile getExternalSdDocumentFile() {
   DocumentFile sdDir = null;
   String extSdFolder = appSettingsManager.GetBaseFolder();
   if (extSdFolder == null || extSdFolder.equals("")) return null;
   Uri uri = Uri.parse(extSdFolder);
   sdDir = DocumentFile.fromTreeUri(getContext(), uri);
   return sdDir;
 }
  /**
   * Get a DocumentFile corresponding to the given file (for writing on ExtSdCard on Android 5). If
   * the file is not existing, it is created.
   *
   * @param file The file.
   * @param isDirectory flag indicating if the file should be a directory.
   * @return The DocumentFile
   */
  public static DocumentFile getDocumentFile(
      final File file, final boolean isDirectory, Context context) {
    String baseFolder = getExtSdCardFolder(file, context);
    boolean originalDirectory = false;
    if (baseFolder == null) {
      return null;
    }

    String relativePath = null;
    try {
      String fullPath = file.getCanonicalPath();
      if (!baseFolder.equals(fullPath)) relativePath = fullPath.substring(baseFolder.length() + 1);
      else originalDirectory = true;
    } catch (IOException e) {
      return null;
    } catch (Exception f) {
      originalDirectory = true;
      // continue
    }
    String as = PreferenceManager.getDefaultSharedPreferences(context).getString("URI", null);

    Uri treeUri = null;
    if (as != null) treeUri = Uri.parse(as);
    if (treeUri == null) {
      return null;
    }

    // start with root of SD card and then parse through document tree.
    DocumentFile document = DocumentFile.fromTreeUri(context, treeUri);
    if (originalDirectory) return document;
    String[] parts = relativePath.split("\\/");
    for (int i = 0; i < parts.length; i++) {
      DocumentFile nextDocument = document.findFile(parts[i]);

      if (nextDocument == null) {
        if ((i < parts.length - 1) || isDirectory) {
          nextDocument = document.createDirectory(parts[i]);
        } else {
          nextDocument = document.createFile("image", parts[i]);
        }
      }
      document = nextDocument;
    }

    return document;
  }