List of usage examples for android.os ParcelFileDescriptor close
@Override public void close() throws IOException
From source file:ca.psiphon.PsiphonTunnel.java
private void stopVpn() { stopTun2Socks();/*from w w w. j a v a 2 s . c om*/ ParcelFileDescriptor tunFd = mTunFd.getAndSet(null); if (tunFd != null) { try { tunFd.close(); } catch (IOException e) { } } mRoutingThroughTunnel.set(false); }
From source file:info.papdt.blacklight.ui.statuses.NewPostActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Image picked, decode if (requestCode == REQUEST_PICK_IMG && resultCode == RESULT_OK) { if (Build.VERSION.SDK_INT >= 19) { try { ParcelFileDescriptor parcelFileDescriptor = getContentResolver() .openFileDescriptor(data.getData(), "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); addPicture(image, null); } catch (FileNotFoundException e) { e.printStackTrace();//w w w . ja va2 s . c o m } catch (IOException e) { e.printStackTrace(); } } else { Cursor cursor = getContentResolver().query(data.getData(), new String[] { MediaStore.Images.Media.DATA }, null, null, null); cursor.moveToFirst(); String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); cursor.close(); // Then decode addPicture(null, filePath); } } else if (requestCode == REQUEST_CAPTURE_PHOTO && resultCode == RESULT_OK) { addPicture(null, Utility.lastPicPath); } else if (resultCode == MultiPicturePicker.PICK_OK) { ArrayList<String> paths = data.getStringArrayListExtra("img"); for (String path : paths) { addPicture(null, path); if (mBitmaps.size() >= 9) { break; } } } }
From source file:com.android.messaging.datamodel.BugleDatabaseOperations.java
/** * Read all the parts for a message/* w w w .j av a 2 s .c om*/ * @param dbWrapper database * @param message read parts for this message * @param checkAttachmentFilesExist check each attachment file and only include if file exists */ private static void readMessagePartsData(final DatabaseWrapper dbWrapper, final MessageData message, final boolean checkAttachmentFilesExist) { final ContentResolver contentResolver = Factory.get().getApplicationContext().getContentResolver(); Cursor cursor = null; try { cursor = dbWrapper.query(DatabaseHelper.PARTS_TABLE, MessagePartData.getProjection(), PartColumns.MESSAGE_ID + "=?", new String[] { message.getMessageId() }, null, null, null); while (cursor.moveToNext()) { final MessagePartData messagePartData = MessagePartData.createFromCursor(cursor); if (checkAttachmentFilesExist && messagePartData.isAttachment() && !UriUtil.isBugleAppResource(messagePartData.getContentUri())) { try { // Test that the file exists before adding the attachment to the draft final ParcelFileDescriptor fileDescriptor = contentResolver .openFileDescriptor(messagePartData.getContentUri(), "r"); if (fileDescriptor != null) { fileDescriptor.close(); message.addPart(messagePartData); } } catch (final IOException e) { // The attachment's temp storage no longer exists, just ignore the file } catch (final SecurityException e) { // Likely thrown by openFileDescriptor due to an expired access grant. if (LogUtil.isLoggable(LogUtil.BUGLE_TAG, LogUtil.DEBUG)) { LogUtil.d(LogUtil.BUGLE_TAG, "uri: " + messagePartData.getContentUri()); } } } else { message.addPart(messagePartData); } } } finally { if (cursor != null) { cursor.close(); } } }
From source file:com.xxxifan.devbox.library.rxfile.RxFile.java
private static Observable<Bitmap> getThumbnailFromUriWithSizeAndKind(final Context context, final Uri data, final int requiredWidth, final int requiredHeight, final int kind) { return Observable.fromCallable(new Func0<Bitmap>() { @Override//from w w w.ja v a2 s . c o m public Bitmap call() { Bitmap bitmap = null; ParcelFileDescriptor parcelFileDescriptor; final BitmapFactory.Options options = new BitmapFactory.Options(); if (requiredWidth > 0 && requiredHeight > 0) { options.inJustDecodeBounds = true; options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight); options.inJustDecodeBounds = false; } if (!isMediaUri(data)) { Log.e(TAG, "Not a media uri"); if (isGoogleDriveDocument(data)) { Log.e(TAG, "Google Drive Uri"); DocumentFile file = DocumentFile.fromSingleUri(context, data); if (file.getType().startsWith(Constants.IMAGE_TYPE) || file.getType().startsWith(Constants.VIDEO_TYPE)) { Log.e(TAG, "Google Drive Uri"); try { parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { e.printStackTrace(); } } } else if (data.getScheme().equals(Constants.FILE)) { Log.e(TAG, "Dropbox or other content provider"); try { parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { e.printStackTrace(); } } else { try { parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { e.printStackTrace(); } } } else { Log.e(TAG, "Uri for thumbnail: " + data.toString()); Log.e(TAG, "Uri for thumbnail: " + data); String[] parts = data.getLastPathSegment().split(":"); String fileId = parts[1]; Cursor cursor = null; try { cursor = context.getContentResolver().query(data, null, null, null, null); if (cursor != null) { Log.e(TAG, "Cursor size: " + cursor.getCount()); if (cursor.moveToFirst()) { if (data.toString().contains(Constants.VIDEO)) { bitmap = MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(), Long.parseLong(fileId), kind, options); } else if (data.toString().contains(Constants.IMAGE)) { Log.e(TAG, "Image Uri"); bitmap = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(), Long.parseLong(fileId), kind, options); } Log.e(TAG, bitmap == null ? "null" : "not null"); } } return bitmap; } catch (Exception e) { Log.e(TAG, "Exception while getting thumbnail:" + e.getMessage()); } finally { if (cursor != null) cursor.close(); } } return bitmap; } }); }
From source file:com.pavlospt.rxfile.RxFile.java
private static Observable<Bitmap> getThumbnailFromUriWithSizeAndKind(final Context context, final Uri data, final int requiredWidth, final int requiredHeight, final int kind) { return Observable.fromCallable(new Func0<Bitmap>() { @Override/*from www.ja v a 2 s. co m*/ public Bitmap call() { Bitmap bitmap = null; ParcelFileDescriptor parcelFileDescriptor; final BitmapFactory.Options options = new BitmapFactory.Options(); if (requiredWidth > 0 && requiredHeight > 0) { options.inJustDecodeBounds = true; options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight); options.inJustDecodeBounds = false; } if (!isMediaUri(data)) { logDebug("Not a media uri:" + data); if (isGoogleDriveDocument(data)) { logDebug("Google Drive Uri:" + data); DocumentFile file = DocumentFile.fromSingleUri(context, data); if (file.getType().startsWith(Constants.IMAGE_TYPE) || file.getType().startsWith(Constants.VIDEO_TYPE)) { logDebug("Google Drive Uri:" + data + " (Video or Image)"); try { parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { logError("Exception:" + e.getMessage() + " line: 209"); e.printStackTrace(); } } } else if (data.getScheme().equals(Constants.FILE)) { logDebug("Dropbox or other DocumentsProvider Uri:" + data); try { parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { logError("Exception:" + e.getMessage() + " line: 223"); e.printStackTrace(); } } else { try { parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data, Constants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); parcelFileDescriptor.close(); return bitmap; } catch (IOException e) { logError("Exception:" + e.getMessage() + " line: 235"); e.printStackTrace(); } } } else { logDebug("Uri for thumbnail:" + data); String[] parts = data.getLastPathSegment().split(":"); String fileId = parts[1]; Cursor cursor = null; try { cursor = context.getContentResolver().query(data, null, null, null, null); if (cursor != null) { logDebug("Cursor size:" + cursor.getCount()); if (cursor.moveToFirst()) { if (data.toString().contains(Constants.VIDEO)) { bitmap = MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(), Long.parseLong(fileId), kind, options); } else if (data.toString().contains(Constants.IMAGE)) { bitmap = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(), Long.parseLong(fileId), kind, options); } } } return bitmap; } catch (Exception e) { logError("Exception:" + e.getMessage() + " line: 266"); } finally { if (cursor != null) cursor.close(); } } return bitmap; } }); }
From source file:com.awrtechnologies.carbudgetsales.MainActivity.java
public String getRealPathFromURIUpdated(Context context, Uri contentUri) { ParcelFileDescriptor parcelFileDescriptor; String path = ""; try {/*from w ww . java 2s.com*/ parcelFileDescriptor = getContentResolver().openFileDescriptor(contentUri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); path = getImagePath(contentUri); parcelFileDescriptor.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return path; }
From source file:com.netcompss.ffmpeg4android_client.BaseWizard.java
public static String getFileNameByUri(Context context, Uri uri) { String fileName = "unknown";// default fileName Uri filePathUri = uri;/*from w w w . j a v a 2 s . co m*/ if (uri.getScheme().toString().compareTo("content") == 0) { ParcelFileDescriptor parcelFileDescriptor; String filename = null; try { FileOutputStream fos = null; parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); String extr = Environment.getExternalStorageDirectory().toString(); File mFolder = new File(extr + "/CHURCH"); if (!mFolder.exists()) { mFolder.mkdir(); } else { mFolder.delete(); mFolder.mkdir(); } String s = "rough.png"; File f = new File(mFolder.getAbsolutePath(), s); filename = f.getAbsolutePath(); Log.d("f", filename); try { fos = new FileOutputStream(f); image.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } parcelFileDescriptor.close(); return filename; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (uri.getScheme().compareTo("file") == 0) { fileName = filePathUri.getPath(); File fill = new File(fileName); if (fill.exists()) { Log.d("exitst", "exist"); ParcelFileDescriptor parcelFileDescriptor; String filename = null; FileOutputStream fos = null; Bitmap image = BitmapFactory.decodeFile(fileName); String extr = Environment.getExternalStorageDirectory().toString(); File mFolder = new File(extr + "/CHURCH"); if (!mFolder.exists()) { mFolder.mkdir(); } else { mFolder.delete(); mFolder.mkdir(); } String s = "rough.png"; File f = new File(mFolder.getAbsolutePath(), s); filename = f.getAbsolutePath(); Log.d("f", filename); try { fos = new FileOutputStream(f); image.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } else { Log.d("not file exitst", "not exist"); } Log.d("file", "file"); } else { fileName = filePathUri.getPath(); Log.d("else", "else"); } return fileName; }
From source file:de.arcus.playmusiclib.PlayMusicManager.java
/** * Exports a track to the sd card//from w w w . ja va 2 s . c om * @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:com.almalence.plugins.capture.video.VideoCapturePlugin.java
/** * Appends mp4 audio/video from {@code anotherFileDescriptor} to * {@code mainFileDescriptor}./*from w w w.j a v a 2s .c o m*/ */ public static DocumentFile appendNew(DocumentFile[] inputFiles) { try { DocumentFile targetFile = inputFiles[0]; int[] inputFilesFds = new int[inputFiles.length]; ArrayList<ParcelFileDescriptor> pfdsList = new ArrayList<ParcelFileDescriptor>(); int i = 0; for (DocumentFile f : inputFiles) { ParcelFileDescriptor pfd = ApplicationScreen.instance.getContentResolver() .openFileDescriptor(f.getUri(), "rw"); pfdsList.add(pfd); inputFilesFds[i] = pfd.getFd(); i++; } if (targetFile.exists() && targetFile.length() > 0) { String tmpFileName = targetFile.getName() + ".tmp"; DocumentFile tmpTargetFile = targetFile.getParentFile().createFile("video/mp4", tmpFileName); ParcelFileDescriptor targetFilePfd = ApplicationScreen.instance.getContentResolver() .openFileDescriptor(tmpTargetFile.getUri(), "rw"); Mp4Editor.appendFds(inputFilesFds, targetFilePfd.getFd()); targetFilePfd.close(); for (ParcelFileDescriptor pfd : pfdsList) { pfd.close(); } return tmpTargetFile; } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.almalence.plugins.capture.video.VideoCapturePlugin.java
/** * Appends mp4 audio/video from {@code anotherFileName} to * {@code mainFileName}.//from w w w . jav a 2 s. c o m */ public static File append(File[] inputFiles) { try { File targetFile = inputFiles[0]; int[] inputFilesFds = new int[inputFiles.length]; ArrayList<ParcelFileDescriptor> pfdsList = new ArrayList<ParcelFileDescriptor>(); int i = 0; for (File f : inputFiles) { ParcelFileDescriptor pfd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_WRITE); pfdsList.add(pfd); inputFilesFds[i] = pfd.getFd(); i++; } if (targetFile.exists() && targetFile.length() > 0) { File tmpTargetFile = new File(targetFile.getAbsolutePath() + ".tmp"); ParcelFileDescriptor targetFilePfd = ParcelFileDescriptor.open(tmpTargetFile, ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_READ_WRITE); Mp4Editor.appendFds(inputFilesFds, targetFilePfd.getFd()); targetFilePfd.close(); for (ParcelFileDescriptor pfd : pfdsList) { pfd.close(); } return tmpTargetFile; } else if (targetFile.createNewFile()) { copyFile(inputFiles[1].getAbsolutePath(), inputFiles[0].getAbsolutePath()); return targetFile; } } catch (IOException e) { e.printStackTrace(); } return null; }