Java Code Examples for android.support.v4.provider.DocumentFile#fromTreeUri()

The following examples show how to use android.support.v4.provider.DocumentFile#fromTreeUri() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SettingsImpl.java    From ToGoZip with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static DocumentFile getDocFile(Context context, @NonNull String dir ) {
    DocumentFile docDir = null;

    if (dir.indexOf(":") >= 0) {
        Uri uri = Uri.parse(dir);

        if ("file".equals(uri.getScheme())) {
            File fileDir = new File(uri.getPath());
            docDir = DocumentFile.fromFile(fileDir);
        } else {
            docDir = DocumentFile.fromTreeUri(context, uri);
        }
    } else {
        docDir = DocumentFile.fromFile(new File(dir));
    }
    return docDir;

}
 
Example 2
Source File: SettingsActivity.java    From ToGoZip with GNU General Public License v3.0 6 votes vote down vote up
@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);

    }
}
 
Example 3
Source File: OPlaylistFragment.java    From YTPlayer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 101) {
        if (resultCode== Activity.RESULT_OK)
            YTutils.showInterstitialAd(activity);
    }
    if (requestCode == 42) {
        Uri treeUri = data.getData();
        DocumentFile pickedDir = DocumentFile.fromTreeUri(activity, treeUri);
        activity.grantUriPermission(activity.getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        activity.getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("ext_sdcard", treeUri.toString());
        editor.apply();

        Toast.makeText(activity, "Permission granted, try to delete file again!", Toast.LENGTH_LONG).show();
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 4
Source File: OTGUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Traverse to a specified path in OTG
 *
 * @param path
 * @param context
 * @param createRecursive flag used to determine whether to create new file while traversing to path,
 *                        in case path is not present. Notably useful in opening an output stream.
 * @return
 */
public static DocumentFile getDocumentFile(String path, Context context, boolean createRecursive) {
    SharedPreferences manager = PreferenceManager.getDefaultSharedPreferences(context);
    String rootUriString = manager.getString(ExplorerActivity.KEY_PREF_OTG, null);

    // start with root of SD card and then parse through document tree.
    DocumentFile rootUri = DocumentFile.fromTreeUri(context, Uri.parse(rootUriString));

    String[] parts = path.split("/");
    for (int i = 0; i < parts.length; i++) {

        if (path.equals("otg:/")) break;
        if (parts[i].equals("otg:") || parts[i].equals("")) continue;
        Log.d(context.getClass().getSimpleName(), "Currently at: " + parts[i]);
        // iterating through the required path to find the end point

        DocumentFile nextDocument = rootUri.findFile(parts[i]);
        if (createRecursive) {
            if (nextDocument == null || !nextDocument.exists()) {
                nextDocument = rootUri.createFile(parts[i].substring(parts[i].lastIndexOf(".")), parts[i]);
                Log.d(context.getClass().getSimpleName(), "NOT FOUND! File created: " + parts[i]);
            }
        }
        rootUri = nextDocument;
    }
    return rootUri;
}
 
Example 5
Source File: FileItem.java    From apkextractor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 构造一个documentFile实例的FileItem
 */
public FileItem(@NonNull Context context, @NonNull Uri treeUri,@Nullable String segments) throws Exception{
    this.context=context;
    DocumentFile documentFile=DocumentFile.fromTreeUri(context, treeUri);
    if(documentFile==null)throw new Exception("Can not get documentFile by the treeUri");
    this.documentFile= DocumentFileUtil.getDocumentFileBySegments(documentFile,segments);
}
 
Example 6
Source File: FileUtils.java    From Rey-MusicPlayer with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
public static DocumentFile getDocumentFile(final File file) {
    String baseFolder = getExtSdCardFolder(file);
    String relativePath = null;

    if (baseFolder == null) {
        return null;
    }

    try {
        String fullPath = file.getCanonicalPath();
        relativePath = fullPath.substring(baseFolder.length() + 1);
    } catch (IOException e) {
        Logger.log(e.getMessage());
        return null;
    }
    Uri treeUri = Common.getInstance().getContentResolver().getPersistedUriPermissions().get(0).getUri();

    if (treeUri == null) {
        return null;
    }

    // start with root of SD card and then parse through document tree.
    DocumentFile document = DocumentFile.fromTreeUri(Common.getInstance(), treeUri);

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

    for (String part : parts) {
        DocumentFile nextDocument = document.findFile(part);
        if (nextDocument != null) {
            document = nextDocument;
        }
    }

    return document;
}
 
Example 7
Source File: TreeUriDownloader.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
TreeUriDownloader(Uri uri, File destFile)
        throws FileNotFoundException, MalformedURLException {
    super(uri, destFile);
    context = FDroidApp.getInstance();
    String path = uri.getEncodedPath();
    int lastEscapedSlash = path.lastIndexOf(ESCAPED_SLASH);
    String pathChunkToEscape = path.substring(lastEscapedSlash + ESCAPED_SLASH.length());
    String escapedPathChunk = Uri.encode(pathChunkToEscape);
    treeUri = uri.buildUpon().encodedPath(path.replace(pathChunkToEscape, escapedPathChunk)).build();
    documentFile = DocumentFile.fromTreeUri(context, treeUri);
}
 
Example 8
Source File: TreeUriScannerIntentService.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {
        return;
    }
    Uri treeUri = intent.getData();
    if (treeUri == null) {
        return;
    }
    Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
    DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);
    searchDirectory(treeFile);
}
 
Example 9
Source File: FileUtil.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
/**
   * 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) {
      final String baseFolder = getExtSdCardFolder(file, context);
      boolean originalDirectory = false;
      if (baseFolder == null) {
          return null;
      }

      String relativePath = null;
      try {
          final 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
      }
      final 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;
      final String[] parts = relativePath.split("\\/");
//Log.d("FileUtil", "relativePath " + relativePath);
      for (int i = 0; i < parts.length; i++) {
          //Log.d("FileUtil", "parts[] " + parts[i]);
	if (document == null) {
		return null;
	}
	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]);
              }
          }
          //Log.d("FileUtil", "nextDocument " + nextDocument);
	document = nextDocument;
      }

      return document;
  }
 
Example 10
Source File: OTGUtil.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
/**
   * Returns an array of list of files at a specific path in OTG
   *
   * @param path    the path to the directory tree, starts with prefix 'otg:/'
   *                Independent of URI (or mount point) for the OTG
   * @param context context for loading
   * @return an array of list of files at the path
   */
  public static ArrayList<BaseFile> getDocumentFilesList(final String path, final Context context, final ContentFragment.LoadFiles updater) {
      final SharedPreferences manager = PreferenceManager.getDefaultSharedPreferences(context);
      final String rootUriString = manager.getString(ExplorerActivity.KEY_PREF_OTG, null);
      DocumentFile rootUri = DocumentFile.fromTreeUri(context, Uri.parse(rootUriString));
      ArrayList<BaseFile> files = new ArrayList<>(1024);

      final String[] parts = path.split("/");
      for (int i = 0; i < parts.length; i++) {

          // first omit 'otg:/' before iterating through DocumentFile
          if (path.equals(OTGUtil.PREFIX_OTG + "/")) break;
          if (parts[i].equals("otg:") || parts[i].equals("")) continue;
          Log.d(context.getClass().getSimpleName(), "Currently at: " + parts[i]);
          // iterating through the required path to find the end point
          rootUri = rootUri.findFile(parts[i]);
      }

long prevUpdate = System.currentTimeMillis();
Log.d(context.getClass().getSimpleName(), "Found URI for: " + rootUri.getName());
      // we have the end point DocumentFile, list the files inside it and return
      for (DocumentFile file : rootUri.listFiles()) {
          try {
              if (file.exists()) {
                  long size = 0;
                  if (!file.isDirectory()) size = file.length();
                  Log.d(context.getClass().getSimpleName(), "Found file: " + file.getName());
                  BaseFile baseFile = new BaseFile(path + "/" + file.getName(),
                          RootHelper.parseDocumentFilePermission(file), file.lastModified(), size, file.isDirectory());
                  baseFile.setName(file.getName());
                  baseFile.setMode(OpenMode.OTG);
                  files.add(baseFile);
			final long present = System.currentTimeMillis();
			if (updater != null && present - prevUpdate > 1000 && !updater.busyNoti) {
				prevUpdate = present;
				updater.publish(files);
				files = new ArrayList<>(1024);
			}
              }
          } catch (Exception e) {
          }
      }
if (updater != null) {
	updater.publish(files);
}
      return files;
  }
 
Example 11
Source File: AndroidPathUtils.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
/**
	 * 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.
	 * @param createDirectories flag indicating if intermediate path directories should be created if not existing.
	 * @return The DocumentFile
	 */
	public static DocumentFile getDocumentFile(@NonNull final File file, final boolean isDirectory,
											   final boolean createDirectories, final Context c) {
//		Log.d("getDocumentFile start", df.format(System.currentTimeMillis()));
		String baseFolder = null;
		baseFolder = getExtSdCardFolder(file, c);
		if (baseFolder == null) {
			return null;
		}
		String relativePath;
		try {
			String fullPath = file.getCanonicalPath();
			relativePath = fullPath.substring(baseFolder.length() + 1);
		} catch (IOException e) {
			return null;
		}

		if (treeUri == null) {
			treeUri = getSharedPreferenceUri("key_internal_uri_extsdcard", c);
			if (treeUri == null) { 
				return null; 
			} 
		}

		// start with root of SD card and then parse through document tree.
		DocumentFile document = DocumentFile.fromTreeUri(c, treeUri);

		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) {
					if (createDirectories) {
						nextDocument = document.createDirectory(parts[i]);
					} else {
						return null;
					}
				} else if (isDirectory) {
					nextDocument = document.createDirectory(parts[i]);
				} else {
					nextDocument = document.createFile("image", parts[i]);
				}
			}
			document = nextDocument;
		}
//		Log.d("getDocumentFile end", df.format(System.currentTimeMillis()));
		return document;
	}
 
Example 12
Source File: TGSafBrowserFactory.java    From tuxguitar with GNU Lesser General Public License v2.1 4 votes vote down vote up
public String createSettingsName(Uri uri) {
	TGActivity activity = TGActivityController.getInstance(this.context).getActivity();
	DocumentFile documentFile = DocumentFile.fromTreeUri(activity, uri);
	return activity.getString(R.string.browser_settings_title_format, documentFile.getName());
}
 
Example 13
Source File: DeleteFileUtils.java    From Gallery-example with GNU General Public License v3.0 2 votes vote down vote up
private static void deleteFileSAF(String url, final Activity activity) {

        if (SDCardUtils.getSDCardUri(activity).isEmpty()) {

            PermissionUtils.askSDCardAccess(activity);

        } else {

            File file = new File(url);

            DocumentFile documentFile = DocumentFile.fromTreeUri(activity, Uri.parse(SDCardUtils.getSDCardUri(activity)));

            String[] parts = (file.getPath()).split("\\/");

            for (int i = 3; i < parts.length; i++) {
                if (documentFile != null) {
                    documentFile = documentFile.findFile(parts[i]);
                }
            }

            if (documentFile == null) {

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, activity.getString(R.string.notFound), Toast.LENGTH_SHORT)
                                .show();

                        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

                        rationaleDialog(activity, activity.getString(R.string.sdcard), activity.getString(R.string.sdcardContent), 2, intent);
                    }
                });

            } else {

                if (documentFile.delete()) {

                    deleteFileFromMediaStore(activity.getContentResolver(), file);

                }
            }
        }
    }