Example usage for android.support.v4.provider DocumentFile fromTreeUri

List of usage examples for android.support.v4.provider DocumentFile fromTreeUri

Introduction

In this page you can find the example usage for android.support.v4.provider DocumentFile fromTreeUri.

Prototype

public static DocumentFile fromTreeUri(Context context, Uri uri) 

Source Link

Usage

From source file:org.dkf.jed2k.android.LollipopFileSystem.java

private static DocumentFile getDirectory(Context context, File dir, boolean create) {
    try {/*from  w  w w .  j av a  2  s  .c  o m*/
        String path = dir.getAbsolutePath();

        String baseFolder = getExtSdCardFolder(context, dir);
        if (baseFolder == null) {
            if (create) {
                return dir.mkdirs() ? DocumentFile.fromFile(dir) : null;
            } else {
                return dir.isDirectory() ? DocumentFile.fromFile(dir) : null;
            }
        }

        baseFolder = combineRoot(baseFolder);

        String fullPath = dir.getAbsolutePath();
        String relativePath = baseFolder.length() < fullPath.length()
                ? fullPath.substring(baseFolder.length() + 1)
                : "";

        String[] segments = relativePath.isEmpty() ? new String[0] : relativePath.split("/");

        Uri rootUri = getDocumentUri(context, new File(baseFolder));
        DocumentFile f = DocumentFile.fromTreeUri(context, rootUri);

        for (int i = 0; i < segments.length; i++) {
            String segment = segments[i];
            DocumentFile child = f.findFile(segment);
            if (child != null) {
                f = child;
            } else {
                if (create) {
                    f = f.createDirectory(segment);
                    if (f == null) {
                        return null;
                    }
                } else {
                    return null;
                }
            }
        }

        return f.isDirectory() ? f : null;
    } catch (Exception e) {
        LOG.error("Error getting directory: {} {}", dir, e);
        return null;
    }
}

From source file:com.frostwire.android.LollipopFileSystem.java

private static DocumentFile getDirectory(Context context, File dir, boolean create) {
    try {/*from   w  ww. jav a 2  s.c  o m*/
        String path = dir.getAbsolutePath();
        DocumentFile cached = CACHE.get(path);
        if (cached != null && cached.isDirectory()) {
            return cached;
        }

        String baseFolder = getExtSdCardFolder(context, dir);
        if (baseFolder == null) {
            if (create) {
                return dir.mkdirs() ? DocumentFile.fromFile(dir) : null;
            } else {
                return dir.isDirectory() ? DocumentFile.fromFile(dir) : null;
            }
        }

        baseFolder = combineRoot(baseFolder);

        String fullPath = dir.getAbsolutePath();
        String relativePath = baseFolder.length() < fullPath.length()
                ? fullPath.substring(baseFolder.length() + 1)
                : "";

        String[] segments = relativePath.split("/");

        Uri rootUri = getDocumentUri(context, new File(baseFolder));
        DocumentFile f = DocumentFile.fromTreeUri(context, rootUri);

        // special FrostWire case
        if (create) {
            if (baseFolder.endsWith("/FrostWire") && !f.exists()) {
                baseFolder = baseFolder.substring(0, baseFolder.length() - 10);
                rootUri = getDocumentUri(context, new File(baseFolder));
                f = DocumentFile.fromTreeUri(context, rootUri);
                f = f.findFile("FrostWire");
                if (f == null) {
                    f = f.createDirectory("FrostWire");
                    if (f == null) {
                        return null;
                    }
                }
            }
        }
        for (String segment : segments) {
            DocumentFile child = f.findFile(segment);
            if (child != null) {
                f = child;
            } else {
                if (create) {
                    f = f.createDirectory(segment);
                    if (f == null) {
                        return null;
                    }
                } else {
                    return null;
                }
            }
        }

        f = f.isDirectory() ? f : null;

        if (f != null) {
            CACHE.put(path, f);
        }

        return f;
    } catch (Throwable e) {
        LOG.error("Error getting directory: " + dir, e);
        return null;
    }
}

From source file:freed.ActivityAbstract.java

@Override
public DocumentFile getExternalSdDocumentFile() {
    DocumentFile sdDir = null;//w  w  w .j  a va 2s . com
    String extSdFolder = appSettingsManager.GetBaseFolder();
    if (extSdFolder == null || extSdFolder.equals(""))
        return null;
    Uri uri = Uri.parse(extSdFolder);
    sdDir = DocumentFile.fromTreeUri(getContext(), uri);
    return sdDir;
}

From source file:org.dkf.jed2k.android.LollipopFileSystem.java

private static DocumentFile getDocument(Context context, File file) {
    try {/* w w  w  .  j av a2 s.c  o  m*/
        String path = file.getAbsolutePath();
        String baseFolder = getExtSdCardFolder(context, file);
        if (baseFolder == null) {
            return file.exists() ? DocumentFile.fromFile(file) : null;
        }

        //baseFolder = combineRoot(baseFolder);

        String fullPath = file.getAbsolutePath();
        String relativePath = baseFolder.length() < fullPath.length()
                ? fullPath.substring(baseFolder.length() + 1)
                : "";

        String[] segments = relativePath.isEmpty() ? new String[0] : relativePath.split("/");

        Uri rootUri = getDocumentUri(context, new File(baseFolder));
        DocumentFile f = DocumentFile.fromTreeUri(context, rootUri);

        for (int i = 0; i < segments.length; i++) {
            String segment = segments[i];
            DocumentFile child = f.findFile(segment);
            if (child != null) {
                f = child;
            } else {
                return null;
            }
        }

        return f;
    } catch (Exception e) {
        LOG.error("Error getting document: {} {}", file, e);
        return null;
    }
}

From source file:com.kanedias.vanilla.audiotag.PluginService.java

/**
 * Write changes through SAF framework - the only way to do it in Android > 4.4 when working with SD card
 * @param activityResponse response with URI contained in. Can be null if tree permission is already given.
 *///from   w  w w .  j a v  a2 s.c om
private void persistThroughSaf(Intent activityResponse) {
    Uri safUri;
    if (mPrefs.contains(PREF_SDCARD_URI)) {
        // no sorcery can allow you to gain URI to the document representing file you've been provided with
        // you have to find it again using now Document API

        // /storage/volume/Music/some.mp3 will become [storage, volume, music, some.mp3]
        List<String> pathSegments = new ArrayList<>(
                Arrays.asList(mAudioFile.getFile().getAbsolutePath().split("/")));
        Uri allowedSdRoot = Uri.parse(mPrefs.getString(PREF_SDCARD_URI, ""));
        safUri = findInDocumentTree(DocumentFile.fromTreeUri(this, allowedSdRoot), pathSegments);
    } else {
        Intent originalSafResponse = activityResponse.getParcelableExtra(EXTRA_PARAM_SAF_P2P);
        safUri = originalSafResponse.getData();
    }

    if (safUri == null) {
        // nothing selected or invalid file?
        Toast.makeText(this, R.string.saf_nothing_selected, Toast.LENGTH_LONG).show();
        return;
    }

    try {
        // we don't have fd-related audiotagger write functions, have to use workaround
        // write audio file to temp cache dir
        // jaudiotagger can't work through file descriptor, sadly
        File original = mAudioFile.getFile();
        File temp = File.createTempFile("tmp-media", '.' + Utils.getExtension(original));
        Utils.copy(original, temp); // jtagger writes only header, we should copy the rest
        temp.deleteOnExit(); // in case of exception it will be deleted too
        mAudioFile.setFile(temp);
        AudioFileIO.write(mAudioFile);

        // retrieve FD from SAF URI
        ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(safUri, "rw");
        if (pfd == null) {
            // should not happen
            Log.e(LOG_TAG, "SAF provided incorrect URI!" + safUri);
            return;
        }

        // now read persisted data and write it to real FD provided by SAF
        FileInputStream fis = new FileInputStream(temp);
        byte[] audioContent = TagEditorUtils.readFully(fis);
        FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
        fos.write(audioContent);
        fos.close();

        // delete temporary file used
        temp.delete();

        // rescan original file
        MediaScannerConnection.scanFile(this, new String[] { original.getAbsolutePath() }, null, null);
        Toast.makeText(this, R.string.file_written_successfully, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(this, getString(R.string.saf_write_error) + e.getLocalizedMessage(), Toast.LENGTH_LONG)
                .show();
        Log.e(LOG_TAG, "Failed to write to file descriptor provided by SAF!", e);
    }
}

From source file:com.frostwire.android.LollipopFileSystem.java

private static DocumentFile getDocument(Context context, File file) {
    try {/*from  ww w  .j  a  va  2  s  .  c o m*/
        String path = file.getAbsolutePath();
        DocumentFile cached = CACHE.get(path);
        if (cached != null) {
            return cached;
        }

        String baseFolder = getExtSdCardFolder(context, file);
        if (baseFolder == null) {
            return file.exists() ? DocumentFile.fromFile(file) : null;
        }

        baseFolder = combineRoot(baseFolder);

        String fullPath = file.getAbsolutePath();
        String relativePath = baseFolder.length() < fullPath.length()
                ? fullPath.substring(baseFolder.length() + 1)
                : "";

        String[] segments = relativePath.split("/");

        Uri rootUri = getDocumentUri(context, new File(baseFolder));
        DocumentFile f = DocumentFile.fromTreeUri(context, rootUri);
        for (String segment : segments) {
            DocumentFile child = f.findFile(segment);
            if (child != null) {
                f = child;
            } else {
                return null;
            }
        }

        if (f != null) {
            CACHE.put(path, f);
        }

        return f;
    } catch (Throwable e) {
        LOG.error("Error getting document: " + file, e);
        return null;
    }
}

From source file:de.k3b.android.toGoZip.SettingsActivity.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static void grandPermission5(Context ctx, Uri data) {
    DocumentFile docPath = DocumentFile.fromTreeUri(ctx, data);
    if (docPath != null) {
        final ContentResolver resolver = ctx.getContentResolver();
        resolver.takePersistableUriPermission(data,
                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    }/* w w  w.  j a va2 s . c  o m*/
}

From source file:com.github.chenxiaolong.dualbootpatcher.FileUtils.java

@NonNull
public static DocumentFile getDocumentFile(@NonNull Context context, @NonNull Uri uri) {
    DocumentFile df = null;//from www. ja  v  a2  s  . co  m

    if (FILE_SCHEME.equals(uri.getScheme())) {
        df = DocumentFile.fromFile(new File(uri.getPath()));
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && SAF_SCHEME.equals(uri.getScheme())
            && SAF_AUTHORITY.equals(uri.getAuthority())) {
        if (DocumentsContract.isDocumentUri(context, uri)) {
            df = DocumentFile.fromSingleUri(context, uri);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && DocumentsContract.isTreeUri(uri)) {
            df = DocumentFile.fromTreeUri(context, uri);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // Best guess is that it's a tree...
            df = DocumentFile.fromTreeUri(context, uri);
        }
    }

    if (df == null) {
        throw new IllegalArgumentException("Invalid URI: " + uri);
    }

    return df;
}

From source file:de.arcus.playmusiclib.PlayMusicManager.java

/**
 * Exports a track to the sd card//from www .  j  av a  2s .  co  m
 * @param musicTrack The music track you want to export
 * @param uri The document tree
 * @return Returns whether the export was successful
 */
public boolean exportMusicTrack(MusicTrack musicTrack, Uri uri, String path) {

    // Check for null
    if (musicTrack == null)
        return false;

    String srcFile = musicTrack.getSourceFile();

    // Could not find the source file
    if (srcFile == null)
        return false;

    String fileTmp = getTempPath() + "/tmp.mp3";

    // Copy to temp path failed
    if (!SuperUserTools.fileCopy(srcFile, fileTmp))
        return false;

    // Encrypt the file
    if (musicTrack.isEncoded()) {
        String fileTmpCrypt = getTempPath() + "/crypt.mp3";

        // Encrypts the file
        if (trackEncrypt(musicTrack, fileTmp, fileTmpCrypt)) {
            // Remove the old tmp file
            FileTools.fileDelete(fileTmp);

            // New tmp file
            fileTmp = fileTmpCrypt;
        } else {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "Encrypting failed! Continue with decrypted file.");
        }
    }

    String dest;
    Uri copyUri = null;
    if (uri.toString().startsWith("file://")) {
        // Build the full path
        dest = uri.buildUpon().appendPath(path).build().getPath();

        String parentDirectory = new File(dest).getParent();
        FileTools.directoryCreate(parentDirectory);
    } else {
        // Complex uri (Lollipop)
        dest = getTempPath() + "/final.mp3";

        // The root
        DocumentFile document = DocumentFile.fromTreeUri(mContext, uri);

        // Creates the subdirectories
        String[] directories = path.split("\\/");
        for (int i = 0; i < directories.length - 1; i++) {
            String directoryName = directories[i];
            boolean found = false;

            // Search all sub elements
            for (DocumentFile subDocument : document.listFiles()) {
                // Directory exists
                if (subDocument.isDirectory() && subDocument.getName().equals(directoryName)) {
                    document = subDocument;
                    found = true;
                    break;
                }
            }

            if (!found) {
                // Create the directory
                document = document.createDirectory(directoryName);
            }
        }

        // Gets the filename
        String filename = directories[directories.length - 1];

        for (DocumentFile subDocument : document.listFiles()) {
            // Directory exists
            if (subDocument.isFile() && subDocument.getName().equals(filename)) {
                // Delete the file
                subDocument.delete();
                break;
            }
        }

        // Create the mp3 file
        document = document.createFile("music/mp3", filename);

        // Create the directories
        copyUri = document.getUri();
    }

    // We want to export the ID3 tags
    if (mID3Enable) {
        // Adds the meta data
        if (!trackWriteID3(musicTrack, fileTmp, dest)) {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "ID3 writer failed! Continue without ID3 tags.");

            // Failed, moving without meta data
            if (!FileTools.fileMove(fileTmp, dest)) {
                Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

                // Could not copy the file
                return false;
            }
        }
    } else {
        // Moving the file
        if (!FileTools.fileMove(fileTmp, dest)) {
            Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

            // Could not copy the file
            return false;
        }
    }

    // We need to copy the file to a uri
    if (copyUri != null) {
        // Lollipop only
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                // Gets the file descriptor
                ParcelFileDescriptor parcelFileDescriptor = mContext.getContentResolver()
                        .openFileDescriptor(copyUri, "w");

                // Gets the output stream
                FileOutputStream fileOutputStream = new FileOutputStream(
                        parcelFileDescriptor.getFileDescriptor());

                // Gets the input stream
                FileInputStream fileInputStream = new FileInputStream(dest);

                // Copy the stream
                FileTools.fileCopy(fileInputStream, fileOutputStream);

                // Close all streams
                fileOutputStream.close();
                fileInputStream.close();
                parcelFileDescriptor.close();

            } catch (FileNotFoundException e) {
                Logger.getInstance().logError("ExportMusicTrack", "File not found!");

                // Could not copy the file
                return false;
            } catch (IOException e) {
                Logger.getInstance().logError("ExportMusicTrack",
                        "Failed to write the document: " + e.toString());

                // Could not copy the file
                return false;
            }
        }
    }

    // Delete temp files
    cleanUp();

    // Adds the file to the media system
    //new MediaScanner(mContext, dest);

    // Done
    return true;
}

From source file:org.totschnig.myexpenses.util.Utils.java

/**
 * @return the directory user has configured in the settings, if not configured yet
 * returns {@link android.content.ContextWrapper#getExternalFilesDir(String)} with argument null
 *//*from w w w .  j  a  v  a 2s .c  om*/
public static DocumentFile getAppDir() {
    String prefString = PrefKey.APP_DIR.getString(null);
    if (prefString != null) {
        Uri pref = Uri.parse(prefString);
        if (pref.getScheme().equals("file")) {
            File appDir = new File(pref.getPath());
            if (appDir.mkdir() || appDir.isDirectory()) {
                return DocumentFile.fromFile(appDir);
            } /* else {
               Utils.reportToAcra(new Exception("Found invalid preference value " + prefString));
              }*/
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //this will return null, if called on a pre-Lolipop device
                DocumentFile documentFile = DocumentFile.fromTreeUri(MyApplication.getInstance(), pref);
                if (dirExistsAndIsWritable(documentFile)) {
                    return documentFile;
                }
            }
        }
    }
    File externalFilesDir = MyApplication.getInstance().getExternalFilesDir(null);
    if (externalFilesDir != null) {
        return DocumentFile.fromFile(externalFilesDir);
    } else {
        String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        AcraHelper.report(new Exception("getExternalFilesDir returned null; " + permission + " : "
                + ContextCompat.checkSelfPermission(MyApplication.getInstance(), permission)));
        return null;
    }
}