List of usage examples for android.support.v4.provider DocumentFile getUri
public abstract Uri getUri();
From source file:org.totschnig.myexpenses.util.Utils.java
/** * @return false if the configured folder is inside the application folder * that will be deleted upon app uninstall and hence user should be * warned about the situation, unless he already has opted to no * longer see this warning//from w w w. j a v a 2s. c om */ @SuppressLint("NewApi") public static boolean checkAppFolderWarning() { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { // return true; // } if (PrefKey.APP_FOLDER_WARNING_SHOWN.getBoolean(false)) { return true; } try { DocumentFile configuredDir = Utils.getAppDir(); if (configuredDir == null) { return true; } File externalFilesDir = MyApplication.getInstance().getExternalFilesDir(null); if (externalFilesDir == null) { return true; } Uri dirUri = configuredDir.getUri(); if (!dirUri.getScheme().equals("file")) { return true; //nothing we can do if we can not compare paths } URI defaultDir = externalFilesDir.getParentFile().getCanonicalFile().toURI(); return defaultDir.relativize(new File(dirUri.getPath()).getCanonicalFile().toURI()).isAbsolute(); } catch (IOException e) { return true; } }
From source file:org.kde.kdeconnect.Plugins.SharePlugin.SharePlugin.java
@Override public boolean onPackageReceived(NetworkPackage np) { try {//from w w w . j av a 2 s . c o m if (np.hasPayload()) { Log.i("SharePlugin", "hasPayload"); final InputStream input = np.getPayload(); final long fileLength = np.getPayloadSize(); final String originalFilename = np.getString("filename", Long.toString(System.currentTimeMillis())); //We need to check for already existing files only when storing in the default path. //User-defined paths use the new Storage Access Framework that already handles this. final boolean customDestination = ShareSettingsActivity.isCustomDestinationEnabled(context); final String defaultPath = ShareSettingsActivity.getDefaultDestinationDirectory().getAbsolutePath(); final String filename = customDestination ? originalFilename : FilesHelper.findNonExistingNameForNewFile(defaultPath, originalFilename); String displayName = FilesHelper.getFileNameWithoutExt(filename); final String mimeType = FilesHelper.getMimeTypeFromFile(filename); if ("*/*".equals(mimeType)) { displayName = filename; } final DocumentFile destinationFolderDocument = ShareSettingsActivity .getDestinationDirectory(context); final DocumentFile destinationDocument = destinationFolderDocument.createFile(mimeType, displayName); final OutputStream destinationOutput = context.getContentResolver() .openOutputStream(destinationDocument.getUri()); final Uri destinationUri = destinationDocument.getUri(); final int notificationId = (int) System.currentTimeMillis(); Resources res = context.getResources(); final NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(res.getString(R.string.incoming_file_title, device.getName())) .setContentText(res.getString(R.string.incoming_file_text, filename)) .setTicker(res.getString(R.string.incoming_file_title, device.getName())) .setSmallIcon(android.R.drawable.stat_sys_download).setAutoCancel(true).setOngoing(true) .setProgress(100, 0, true); final NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build()); new Thread(new Runnable() { @Override public void run() { boolean successful = true; try { byte data[] = new byte[1024]; long progress = 0, prevProgressPercentage = 0; int count; while ((count = input.read(data)) >= 0) { progress += count; destinationOutput.write(data, 0, count); if (fileLength > 0) { if (progress >= fileLength) break; long progressPercentage = (progress * 100 / fileLength); if (progressPercentage != prevProgressPercentage) { prevProgressPercentage = progressPercentage; builder.setProgress(100, (int) progressPercentage, false); NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build()); } } //else Log.e("SharePlugin", "Infinite loop? :D"); } destinationOutput.flush(); } catch (Exception e) { successful = false; Log.e("SharePlugin", "Receiver thread exception"); e.printStackTrace(); } finally { try { destinationOutput.close(); } catch (Exception e) { } try { input.close(); } catch (Exception e) { } } try { Log.i("SharePlugin", "Transfer finished: " + destinationUri.getPath()); //Update the notification and allow to open the file from it Resources res = context.getResources(); String message = successful ? res.getString(R.string.received_file_title, device.getName()) : res.getString(R.string.received_file_fail_title, device.getName()); NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(message).setTicker(message) .setSmallIcon(android.R.drawable.stat_sys_download_done).setAutoCancel(true); if (successful) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(destinationUri, mimeType); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addNextIntent(intent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentText( res.getString(R.string.received_file_text, destinationDocument.getName())) .setContentIntent(resultPendingIntent); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean("share_notification_preference", true)) { builder.setDefaults(Notification.DEFAULT_ALL); } NotificationHelper.notifyCompat(notificationManager, notificationId, builder.build()); if (successful) { if (!customDestination && Build.VERSION.SDK_INT >= 12) { Log.i("SharePlugin", "Adding to downloads"); DownloadManager manager = (DownloadManager) context .getSystemService(Context.DOWNLOAD_SERVICE); manager.addCompletedDownload(destinationUri.getLastPathSegment(), device.getName(), true, mimeType, destinationUri.getPath(), fileLength, false); } else { //Make sure it is added to the Android Gallery anyway MediaStoreHelper.indexFile(context, destinationUri); } } } catch (Exception e) { Log.e("SharePlugin", "Receiver thread exception"); e.printStackTrace(); } } }).start(); } else if (np.has("text")) { Log.i("SharePlugin", "hasText"); String text = np.getString("text"); if (Build.VERSION.SDK_INT >= 11) { ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); cm.setText(text); } else { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(text); } Toast.makeText(context, R.string.shareplugin_text_saved, Toast.LENGTH_LONG).show(); } else if (np.has("url")) { String url = np.getString("url"); Log.i("SharePlugin", "hasUrl: " + url); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (openUrlsDirectly) { context.startActivity(browserIntent); } else { Resources res = context.getResources(); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); stackBuilder.addNextIntent(browserIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); Notification noti = new NotificationCompat.Builder(context) .setContentTitle(res.getString(R.string.received_url_title, device.getName())) .setContentText(res.getString(R.string.received_url_text, url)) .setContentIntent(resultPendingIntent) .setTicker(res.getString(R.string.received_url_title, device.getName())) .setSmallIcon(R.drawable.ic_notification).setAutoCancel(true) .setDefaults(Notification.DEFAULT_ALL).build(); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); NotificationHelper.notifyCompat(notificationManager, (int) System.currentTimeMillis(), noti); } } else { Log.e("SharePlugin", "Error: Nothing attached!"); } } catch (Exception e) { Log.e("SharePlugin", "Exception"); e.printStackTrace(); } return true; }
From source file:com.amaze.filemanager.utils.files.GenericCopyUtil.java
/** * Starts copy of file//w ww . j av a2 s .co m * Supports : {@link File}, {@link jcifs.smb.SmbFile}, {@link DocumentFile}, {@link CloudStorage} * @param lowOnMemory defines whether system is running low on memory, in which case we'll switch to * using streams instead of channel which maps the who buffer in memory. * TODO: Use buffers even on low memory but don't map the whole file to memory but * parts of it, and transfer each part instead. */ private void startCopy(boolean lowOnMemory) throws IOException { FileInputStream inputStream = null; FileOutputStream outputStream = null; FileChannel inChannel = null; FileChannel outChannel = null; BufferedInputStream bufferedInputStream = null; BufferedOutputStream bufferedOutputStream = null; try { // initializing the input channels based on file types if (mSourceFile.isOtgFile()) { // source is in otg ContentResolver contentResolver = mContext.getContentResolver(); DocumentFile documentSourceFile = OTGUtil.getDocumentFile(mSourceFile.getPath(), mContext, false); bufferedInputStream = new BufferedInputStream( contentResolver.openInputStream(documentSourceFile.getUri()), DEFAULT_BUFFER_SIZE); } else if (mSourceFile.isSmb()) { // source is in smb bufferedInputStream = new BufferedInputStream(mSourceFile.getInputStream(), DEFAULT_BUFFER_SIZE); } else if (mSourceFile.isSftp()) { bufferedInputStream = new BufferedInputStream(mSourceFile.getInputStream(mContext), DEFAULT_BUFFER_SIZE); } else if (mSourceFile.isDropBoxFile()) { CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX); bufferedInputStream = new BufferedInputStream( cloudStorageDropbox.download(CloudUtil.stripPath(OpenMode.DROPBOX, mSourceFile.getPath()))); } else if (mSourceFile.isBoxFile()) { CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX); bufferedInputStream = new BufferedInputStream( cloudStorageBox.download(CloudUtil.stripPath(OpenMode.BOX, mSourceFile.getPath()))); } else if (mSourceFile.isGoogleDriveFile()) { CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE); bufferedInputStream = new BufferedInputStream( cloudStorageGdrive.download(CloudUtil.stripPath(OpenMode.GDRIVE, mSourceFile.getPath()))); } else if (mSourceFile.isOneDriveFile()) { CloudStorage cloudStorageOnedrive = dataUtils.getAccount(OpenMode.ONEDRIVE); bufferedInputStream = new BufferedInputStream(cloudStorageOnedrive .download(CloudUtil.stripPath(OpenMode.ONEDRIVE, mSourceFile.getPath()))); } else { // source file is neither smb nor otg; getting a channel from direct file instead of stream File file = new File(mSourceFile.getPath()); if (FileUtil.isReadable(file)) { if (mTargetFile.isOneDriveFile() || mTargetFile.isDropBoxFile() || mTargetFile.isGoogleDriveFile() || mTargetFile.isBoxFile() || lowOnMemory) { // our target is cloud, we need a stream not channel bufferedInputStream = new BufferedInputStream(new FileInputStream(file)); } else { inChannel = new RandomAccessFile(file, "r").getChannel(); } } else { ContentResolver contentResolver = mContext.getContentResolver(); DocumentFile documentSourceFile = FileUtil.getDocumentFile(file, mSourceFile.isDirectory(), mContext); bufferedInputStream = new BufferedInputStream( contentResolver.openInputStream(documentSourceFile.getUri()), DEFAULT_BUFFER_SIZE); } } // initializing the output channels based on file types if (mTargetFile.isOtgFile()) { // target in OTG, obtain streams from DocumentFile Uri's ContentResolver contentResolver = mContext.getContentResolver(); DocumentFile documentTargetFile = OTGUtil.getDocumentFile(mTargetFile.getPath(), mContext, true); bufferedOutputStream = new BufferedOutputStream( contentResolver.openOutputStream(documentTargetFile.getUri()), DEFAULT_BUFFER_SIZE); } else if (mTargetFile.isSftp()) { bufferedOutputStream = new BufferedOutputStream(mTargetFile.getOutputStream(mContext), DEFAULT_BUFFER_SIZE); } else if (mTargetFile.isSmb()) { bufferedOutputStream = new BufferedOutputStream(mTargetFile.getOutputStream(mContext), DEFAULT_BUFFER_SIZE); } else if (mTargetFile.isDropBoxFile()) { // API doesn't support output stream, we'll upload the file directly CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX); if (mSourceFile.isDropBoxFile()) { // we're in the same provider, use api method cloudStorageDropbox.copy(CloudUtil.stripPath(OpenMode.DROPBOX, mSourceFile.getPath()), CloudUtil.stripPath(OpenMode.DROPBOX, mTargetFile.getPath())); return; } else { cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, mTargetFile.getPath()), bufferedInputStream, mSourceFile.getSize(), true); return; } } else if (mTargetFile.isBoxFile()) { // API doesn't support output stream, we'll upload the file directly CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX); if (mSourceFile.isBoxFile()) { // we're in the same provider, use api method cloudStorageBox.copy(CloudUtil.stripPath(OpenMode.BOX, mSourceFile.getPath()), CloudUtil.stripPath(OpenMode.BOX, mTargetFile.getPath())); return; } else { cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, mTargetFile.getPath()), bufferedInputStream, mSourceFile.getSize(), true); bufferedInputStream.close(); return; } } else if (mTargetFile.isGoogleDriveFile()) { // API doesn't support output stream, we'll upload the file directly CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE); if (mSourceFile.isGoogleDriveFile()) { // we're in the same provider, use api method cloudStorageGdrive.copy(CloudUtil.stripPath(OpenMode.GDRIVE, mSourceFile.getPath()), CloudUtil.stripPath(OpenMode.GDRIVE, mTargetFile.getPath())); return; } else { cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, mTargetFile.getPath()), bufferedInputStream, mSourceFile.getSize(), true); bufferedInputStream.close(); return; } } else if (mTargetFile.isOneDriveFile()) { // API doesn't support output stream, we'll upload the file directly CloudStorage cloudStorageOnedrive = dataUtils.getAccount(OpenMode.ONEDRIVE); if (mSourceFile.isOneDriveFile()) { // we're in the same provider, use api method cloudStorageOnedrive.copy(CloudUtil.stripPath(OpenMode.ONEDRIVE, mSourceFile.getPath()), CloudUtil.stripPath(OpenMode.ONEDRIVE, mTargetFile.getPath())); return; } else { cloudStorageOnedrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, mTargetFile.getPath()), bufferedInputStream, mSourceFile.getSize(), true); bufferedInputStream.close(); return; } } else { // copying normal file, target not in OTG File file = new File(mTargetFile.getPath()); if (FileUtil.isWritable(file)) { if (lowOnMemory) { bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); } else { outChannel = new RandomAccessFile(file, "rw").getChannel(); } } else { ContentResolver contentResolver = mContext.getContentResolver(); DocumentFile documentTargetFile = FileUtil.getDocumentFile(file, mTargetFile.isDirectory(), mContext); bufferedOutputStream = new BufferedOutputStream( contentResolver.openOutputStream(documentTargetFile.getUri()), DEFAULT_BUFFER_SIZE); } } if (bufferedInputStream != null) { if (bufferedOutputStream != null) copyFile(bufferedInputStream, bufferedOutputStream); else if (outChannel != null) { copyFile(bufferedInputStream, outChannel); } } else if (inChannel != null) { if (bufferedOutputStream != null) copyFile(inChannel, bufferedOutputStream); else if (outChannel != null) copyFile(inChannel, outChannel); } } catch (IOException e) { e.printStackTrace(); Log.d(getClass().getSimpleName(), "I/O Error!"); throw new IOException(); } catch (OutOfMemoryError e) { e.printStackTrace(); // we ran out of memory to map the whole channel, let's switch to streams AppConfig.toast(mContext, mContext.getString(R.string.copy_low_memory)); startCopy(true); } finally { try { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); if (bufferedInputStream != null) bufferedInputStream.close(); if (bufferedOutputStream != null) bufferedOutputStream.close(); } catch (IOException e) { e.printStackTrace(); // failure in closing stream } //If target file is copied onto the device and copy was successful, trigger media store //rescan if ((mTargetFile.isLocal() || mTargetFile.isOtgFile()) && mTargetFile.exists(mContext)) { DocumentFile documentFile = FileUtil.getDocumentFile(mTargetFile.getFile(), false, mContext); //If FileUtil.getDocumentFile() returns null, fall back to DocumentFile.fromFile() if (documentFile == null) documentFile = DocumentFile.fromFile(mTargetFile.getFile()); FileUtils.scanFile(documentFile.getUri(), mContext); } } }
From source file:com.amaze.filemanager.utils.files.FileUtils.java
public static void openWith(final DocumentFile f, final Context c, final boolean useNewStack) { MaterialDialog.Builder a = new MaterialDialog.Builder(c); a.title(c.getString(R.string.openas)); String[] items = new String[] { c.getString(R.string.text), c.getString(R.string.image), c.getString(R.string.video), c.getString(R.string.audio), c.getString(R.string.database), c.getString(R.string.other) }; a.items(items).itemsCallback((materialDialog, view, i, charSequence) -> { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); switch (i) { case 0:// ww w.j av a2s . co m if (useNewStack) applyNewDocFlag(intent); intent.setDataAndType(f.getUri(), "text/*"); break; case 1: intent.setDataAndType(f.getUri(), "image/*"); break; case 2: intent.setDataAndType(f.getUri(), "video/*"); break; case 3: intent.setDataAndType(f.getUri(), "audio/*"); break; case 4: intent = new Intent(c, DatabaseViewerActivity.class); intent.putExtra("path", f.getUri()); break; case 5: intent.setDataAndType(f.getUri(), "*/*"); break; } try { c.startActivity(intent); } catch (Exception e) { Toast.makeText(c, R.string.noappfound, Toast.LENGTH_SHORT).show(); openWith(f, c, useNewStack); } }); a.build().show(); }
From source file:com.frostwire.android.LollipopFileSystem.java
@Override public File[] listFiles(File file, FileFilter filter) { try {/* w w w .ja v a 2 s . c o m*/ File[] files = file.listFiles(filter); if (files != null) { return files; } } catch (Throwable e) { // ignore, try with SAF } LOG.warn("Using SAF for listFiles, could be a costly operation"); DocumentFile f = getDirectory(app, file, false); if (f == null) { return null; // does not exists } DocumentFile[] files = f.listFiles(); if (filter != null && files != null) { List<File> result = new ArrayList<>(files.length); for (DocumentFile file1 : files) { Uri uri = file1.getUri(); String path = getDocumentPath(uri); if (path == null) { continue; } File child = new File(path); if (filter.accept(child)) { result.add(child); } } return result.toArray(new File[0]); } return new File[0]; }
From source file:com.kanedias.vanilla.lyrics.LyricsShowActivity.java
/** * Write lyrics to *.lrc file through SAF framework - the only way to do it in Android > 4.4 when working with SD card */// w w w . j a v a 2 s .c o m private void writeThroughSaf(byte[] data, File original, String name) { DocumentFile originalRef; 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 now using Document API // /storage/volume/Music/some.mp3 will become [storage, volume, music, some.mp3] List<String> pathSegments = new ArrayList<>(Arrays.asList(original.getAbsolutePath().split("/"))); Uri allowedSdRoot = Uri.parse(mPrefs.getString(PREF_SDCARD_URI, "")); originalRef = findInDocumentTree(DocumentFile.fromTreeUri(this, allowedSdRoot), pathSegments); } else { // user will click the button again return; } if (originalRef == null || originalRef.getParentFile() == null) { // nothing selected or invalid file? Toast.makeText(this, R.string.saf_nothing_selected, Toast.LENGTH_LONG).show(); return; } DocumentFile lrcFileRef = originalRef.getParentFile().createFile("image/*", name); if (lrcFileRef == null) { // couldn't create file? Toast.makeText(this, R.string.saf_write_error, Toast.LENGTH_LONG).show(); return; } try { ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(lrcFileRef.getUri(), "rw"); if (pfd == null) { // should not happen Log.e(LOG_TAG, "SAF provided incorrect URI!" + lrcFileRef.getUri()); return; } FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor()); fos.write(data); fos.close(); // rescan original file 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.anjalimacwan.MainActivity.java
@TargetApi(Build.VERSION_CODES.KITKAT) @Override/*from w w w. j a v a2 s. com*/ public void onActivityResult(int requestCode, int resultCode, Intent resultData) { if (resultCode == RESULT_OK && resultData != null) { successful = true; if (requestCode == IMPORT) { Uri uri = resultData.getData(); ClipData clipData = resultData.getClipData(); if (uri != null) successful = importNote(uri); else if (clipData != null) for (int i = 0; i < clipData.getItemCount(); i++) { successful = importNote(clipData.getItemAt(i).getUri()); } // Show toast notification showToast(successful ? (uri == null ? R.string.notes_imported_successfully : R.string.note_imported_successfully) : R.string.error_importing_notes); // Send broadcast to NoteListFragment to refresh list of notes Intent listNotesIntent = new Intent(); listNotesIntent.setAction("com.anjalimacwan.LIST_NOTES"); LocalBroadcastManager.getInstance(this).sendBroadcast(listNotesIntent); } else if (requestCode == EXPORT) { try { saveExportedNote(loadNote(filesToExport[fileBeingExported].toString()), resultData.getData()); } catch (IOException e) { successful = false; } fileBeingExported++; if (fileBeingExported < filesToExport.length) reallyExportNote(); else showToast(successful ? (fileBeingExported == 1 ? R.string.note_exported_to : R.string.notes_exported_to) : R.string.error_exporting_notes); } else if (requestCode == EXPORT_TREE) { DocumentFile tree = DocumentFile.fromTreeUri(this, resultData.getData()); for (Object exportFilename : filesToExport) { try { DocumentFile file = tree.createFile("text/plain", generateFilename(loadNoteTitle(exportFilename.toString()))); saveExportedNote(loadNote(exportFilename.toString()), file.getUri()); } catch (IOException e) { successful = false; } } showToast(successful ? R.string.notes_exported_to : R.string.error_exporting_notes); } } }
From source file:com.kanedias.vanilla.audiotag.PluginService.java
/** * Finds needed file through Document API for SAF. It's not optimized yet - you can still gain wrong URI on * files such as "/a/b/c.mp3" and "/b/a/c.mp3", but I consider it complete enough to be usable. * @param currentDir - document file representing current dir of search * @param remainingPathSegments - path segments that are left to find * @return URI for found file. Null if nothing found. *///from w w w . ja v a 2s . co m @Nullable private Uri findInDocumentTree(DocumentFile currentDir, List<String> remainingPathSegments) { for (DocumentFile file : currentDir.listFiles()) { int index = remainingPathSegments.indexOf(file.getName()); if (index == -1) { continue; } if (file.isDirectory()) { remainingPathSegments.remove(file.getName()); return findInDocumentTree(file, remainingPathSegments); } if (file.isFile() && index == remainingPathSegments.size() - 1) { // got to the last part return file.getUri(); } } return null; }
From source file:org.dkf.jed2k.android.LollipopFileSystem.java
public Pair<ParcelFileDescriptor, DocumentFile> openFD(File file, String mode) { if (!("r".equals(mode) || "w".equals(mode) || "rw".equals(mode))) { LOG.error("Only r, w or rw modes supported"); return null; }/* ww w. ja v a 2s . c o m*/ DocumentFile f = getFile(app, file, true); if (f == null) { LOG.error("Unable to obtain or create document for file: {}", file); return null; } try { ContentResolver cr = app.getContentResolver(); return Pair.create(cr.openFileDescriptor(f.getUri(), mode), f); } catch (Exception e) { LOG.error("Unable to get native fd", e); return null; } }
From source file:com.frostwire.android.LollipopFileSystem.java
public int openFD(File file, String mode) { if (!("r".equals(mode) || "w".equals(mode) || "rw".equals(mode))) { LOG.error("Only r, w or rw modes supported"); return -1; }/*w w w . ja v a 2 s . c om*/ DocumentFile f = getFile(app, file, true); if (f == null) { LOG.error("Unable to obtain or create document for file: " + file); return -1; } try { ContentResolver cr = app.getContentResolver(); ParcelFileDescriptor fd = cr.openFileDescriptor(f.getUri(), mode); if (fd == null) { return -1; } return fd.detachFd(); } catch (Throwable e) { LOG.error("Unable to get native fd", e); return -1; } }