List of usage examples for android.os ParcelFileDescriptor getFileDescriptor
public FileDescriptor getFileDescriptor()
From source file:br.com.viniciuscr.notification2android.mediaPlayer.MusicUtils.java
private static Bitmap getArtworkQuick(Context context, long album_id, int w, int h) { // NOTE: There is in fact a 1 pixel border on the right side in the ImageView // used to display this drawable. Take it into account now, so we don't have to // scale later. w -= 1;// w w w .j a v a 2s . c o m ContentResolver res = context.getContentResolver(); Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id); if (uri != null) { ParcelFileDescriptor fd = null; try { fd = res.openFileDescriptor(uri, "r"); int sampleSize = 1; // Compute the closest power-of-two scale factor // and pass that to sBitmapOptionsCache.inSampleSize, which will // result in faster decoding and better quality sBitmapOptionsCache.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache); int nextWidth = sBitmapOptionsCache.outWidth >> 1; int nextHeight = sBitmapOptionsCache.outHeight >> 1; while (nextWidth > w && nextHeight > h) { sampleSize <<= 1; nextWidth >>= 1; nextHeight >>= 1; } sBitmapOptionsCache.inSampleSize = sampleSize; sBitmapOptionsCache.inJustDecodeBounds = false; Bitmap b = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache); if (b != null) { // finally rescale to exactly the size we need if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) { Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true); // Bitmap.createScaledBitmap() can return the same bitmap if (tmp != b) b.recycle(); b = tmp; } } return b; } catch (FileNotFoundException e) { } finally { try { if (fd != null) fd.close(); } catch (IOException e) { } } } return null; }
From source file:eu.faircode.netguard.SinkholeService.java
private void startDebug(final ParcelFileDescriptor pfd) { if (!debug)// w w w .ja va 2s. com return; thread = new Thread(new Runnable() { @Override public void run() { try { FileInputStream in = new FileInputStream(pfd.getFileDescriptor()); FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor()); ByteBuffer buffer = ByteBuffer.allocate(32767); buffer.order(ByteOrder.BIG_ENDIAN); Log.i(TAG, "Start receiving"); while (!Thread.currentThread().isInterrupted() && pfd.getFileDescriptor() != null && pfd.getFileDescriptor().valid()) try { buffer.clear(); int length = in.read(buffer.array()); if (length > 0) { buffer.limit(length); Packet pkt = new Packet(buffer); if (pkt.IPv4.protocol == Packet.IPv4Header.TCP && pkt.TCP.SYN) { int uid = pkt.getUid4(); if (uid < 0) Log.w(TAG, "uid not found"); String[] pkg = getPackageManager().getPackagesForUid(uid); if (pkg == null) pkg = new String[] { uid == 0 ? "root" : "unknown" }; Log.i(TAG, "Connect " + pkt.IPv4.destinationAddress + ":" + pkt.TCP.destinationPort + " uid=" + uid + " pkg=" + pkg[0]); // Send RST pkt.swapAddresses(); pkt.TCP.clearFlags(); pkt.TCP.RST = true; long ack = pkt.TCP.acknowledgementNumber; pkt.TCP.acknowledgementNumber = (pkt.TCP.sequenceNumber + 1) & 0xFFFFFFFFL; pkt.TCP.sequenceNumber = (ack + 1) & 0xFFFFFFFFL; pkt.send(out); } } } catch (Throwable ex) { Log.e(TAG, ex.toString()); } Log.i(TAG, "End receiving"); } catch (Throwable ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } } }); thread.start(); }
From source file:uno.weichen.abnd10_inventoryapp.DetailActivity.java
private Bitmap getBitmapFromUri(Uri uri) { ParcelFileDescriptor parcelFileDescriptor = null; try {/* ww w . j a v a 2 s . co m*/ parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); return image; } catch (Exception e) { Log.e(LOG_TAG, getString(R.string.get_bitmap_from_uri_exception), e); return null; } finally { try { if (parcelFileDescriptor != null) { parcelFileDescriptor.close(); } } catch (IOException e) { e.printStackTrace(); Log.e(LOG_TAG, getString(R.string.get_bitmap_from_uri_error)); } } }
From source file:com.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.java
protected void processGooglePhotosMedia(String path, String extension) throws Exception { if (BuildConfig.DEBUG) { Log.i(TAG, "Google photos Started"); Log.i(TAG, "URI: " + path); Log.i(TAG, "Extension: " + extension); }/*from w ww .j a v a2s .c om*/ String retrievedExtension = checkExtension(Uri.parse(path)); if (retrievedExtension != null && !TextUtils.isEmpty(retrievedExtension)) { extension = "." + retrievedExtension; } try { filePath = FileUtils.getDirectory(foldername) + File.separator + Calendar.getInstance().getTimeInMillis() + extension; ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver() .openFileDescriptor(Uri.parse(path), "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); InputStream inputStream = new FileInputStream(fileDescriptor); BufferedInputStream reader = new BufferedInputStream(inputStream); BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(filePath)); byte[] buf = new byte[2048]; int len; while ((len = reader.read(buf)) > 0) { outStream.write(buf, 0, len); } outStream.flush(); outStream.close(); inputStream.close(); process(); } catch (FileNotFoundException e) { e.printStackTrace(); throw e; } catch (Exception e) { e.printStackTrace(); throw e; } if (BuildConfig.DEBUG) { Log.i(TAG, "Picasa Done"); } }
From source file:java_lang_programming.com.android_media_demo.article94.java.ImageDecoderActivity.java
/** * Bitmap??//from ww w. j av a 2 s. com * * @param context * @param uri ?Uri * @return Bitmap */ private @Nullable Bitmap getBitmap(@NonNull Context context, @NonNull Uri uri) { final ParcelFileDescriptor parcelFileDescriptor; try { parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r"); } catch (FileNotFoundException e) { e.getStackTrace(); return null; } final FileDescriptor fileDescriptor; if (parcelFileDescriptor != null) { fileDescriptor = parcelFileDescriptor.getFileDescriptor(); } else { // ParcelFileDescriptor was null for given Uri: [" + mInputUri + "]" return null; } final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); if (options.outWidth == -1 || options.outHeight == -1) { // "Bounds for bitmap could not be retrieved from the Uri: [" + mInputUri + "]" return null; } int orientation = getOrientation(uri); int rotation = getRotation(orientation); Matrix transformMatrix = new Matrix(); transformMatrix.setRotate(rotation); // ??? WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y; int reqWidth = Math.min(width, options.outWidth); int reqHeight = Math.min(height, options.outHeight); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; Bitmap decodeSampledBitmap = null; boolean decodeAttemptSuccess = false; while (!decodeAttemptSuccess) { try { decodeSampledBitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options); decodeAttemptSuccess = true; } catch (OutOfMemoryError error) { Log.e("", "doInBackground: BitmapFactory.decodeFileDescriptor: ", error); options.inSampleSize *= 2; } } // ?? decodeSampledBitmap = transformBitmap(decodeSampledBitmap, transformMatrix); return decodeSampledBitmap; }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Decrypt and read content section of this document, writing it into the * given pipe.//from w w w .j a v a 2 s . c o m * <p/> * Pipe is left open, so caller is responsible for calling * {@link ParcelFileDescriptor#close()} or * {@link ParcelFileDescriptor#closeWithError(String)}. * * @param contentOut write end of a pipe. * @throws DigestException if content fails MAC check. Some or all content * may have already been written to the pipe when the MAC is * validated. */ public void readContent(ParcelFileDescriptor contentOut) throws IOException, GeneralSecurityException { final RandomAccessFile f = new RandomAccessFile(mFile, "r"); try { assertMagic(f); if (f.length() <= CONTENT_OFFSET) { throw new IOException("Document has no content"); } // Skip over metadata section f.seek(CONTENT_OFFSET); readSection(f, new FileOutputStream(contentOut.getFileDescriptor())); } finally { f.close(); } }
From source file:com.kanedias.vanilla.audiotag.PluginService.java
/** * This plugin also has P2P functionality with others. It provides generic way to * read and write tags for the file./*w ww . j a v a 2s.co m*/ * <br/> * If intent is passed with EXTRA_PARAM_P2P and READ then EXTRA_PARAM_P2P_KEY is considered * as an array of field keys to retrieve from file. The values read are written in the same order * into answer intent into EXTRA_PARAM_P2P_VAL. * <br/> * If intent is passed with EXTRA_PARAM_P2P and WRITE then EXTRA_PARAM_P2P_KEY is considered * as an array of field keys to write to file. EXTRA_PARAM_P2P_VAL represents values to be written in * the same order. * */ private void handleP2pIntent() { String request = mLaunchIntent.getStringExtra(EXTRA_PARAM_P2P); switch (request) { case P2P_WRITE_TAG: { String[] fields = mLaunchIntent.getStringArrayExtra(EXTRA_PARAM_P2P_KEY); String[] values = mLaunchIntent.getStringArrayExtra(EXTRA_PARAM_P2P_VAL); for (int i = 0; i < fields.length; ++i) { try { FieldKey key = FieldKey.valueOf(fields[i]); mTag.setField(key, values[i]); } catch (IllegalArgumentException iae) { Log.e(LOG_TAG, "Invalid tag requested: " + fields[i], iae); Toast.makeText(this, R.string.invalid_tag_requested, Toast.LENGTH_SHORT).show(); } catch (FieldDataInvalidException e) { // should not happen Log.e(LOG_TAG, "Error writing tag", e); } } writeFile(); break; } case P2P_READ_TAG: { String[] fields = mLaunchIntent.getStringArrayExtra(EXTRA_PARAM_P2P_KEY); ApplicationInfo responseApp = mLaunchIntent.getParcelableExtra(EXTRA_PARAM_PLUGIN_APP); String[] values = new String[fields.length]; for (int i = 0; i < fields.length; ++i) { try { FieldKey key = FieldKey.valueOf(fields[i]); values[i] = mTag.getFirst(key); } catch (IllegalArgumentException iae) { Log.e(LOG_TAG, "Invalid tag requested: " + fields[i], iae); Toast.makeText(this, R.string.invalid_tag_requested, Toast.LENGTH_SHORT).show(); } } Intent response = new Intent(ACTION_LAUNCH_PLUGIN); response.putExtra(EXTRA_PARAM_P2P, P2P_READ_TAG); response.setPackage(responseApp.packageName); response.putExtra(EXTRA_PARAM_P2P_VAL, values); startService(response); break; } case P2P_READ_ART: { ApplicationInfo responseApp = mLaunchIntent.getParcelableExtra(EXTRA_PARAM_PLUGIN_APP); Artwork cover = mTag.getFirstArtwork(); Uri uri = null; try { if (cover == null) { Log.w(LOG_TAG, "Artwork is not present for file " + mAudioFile.getFile().getName()); break; } File coversDir = new File(getCacheDir(), "covers"); if (!coversDir.exists() && !coversDir.mkdir()) { Log.e(LOG_TAG, "Couldn't create dir for covers! Path " + getCacheDir()); break; } // cleanup old images for (File oldImg : coversDir.listFiles()) { if (!oldImg.delete()) { Log.w(LOG_TAG, "Couldn't delete old image file! Path " + oldImg); } } // write artwork to file File coverTmpFile = new File(coversDir, UUID.randomUUID().toString()); FileOutputStream fos = new FileOutputStream(coverTmpFile); fos.write(cover.getBinaryData()); fos.close(); // create sharable uri uri = FileProvider.getUriForFile(this, "com.kanedias.vanilla.audiotag.fileprovider", coverTmpFile); } catch (IOException e) { Log.e(LOG_TAG, "Couldn't write to cache file", e); Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } finally { // share uri if created successfully Intent response = new Intent(ACTION_LAUNCH_PLUGIN); response.putExtra(EXTRA_PARAM_P2P, P2P_READ_ART); response.setPackage(responseApp.packageName); if (uri != null) { grantUriPermission(responseApp.packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION); response.putExtra(EXTRA_PARAM_P2P_VAL, uri); } startService(response); } break; } case P2P_WRITE_ART: { Uri imgLink = mLaunchIntent.getParcelableExtra(EXTRA_PARAM_P2P_VAL); try { ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(imgLink, "r"); if (pfd == null) { return; } FileInputStream fis = new FileInputStream(pfd.getFileDescriptor()); byte[] imgBytes = TagEditorUtils.readFully(fis); Artwork cover = new AndroidArtwork(); cover.setBinaryData(imgBytes); cover.setMimeType(ImageFormats.getMimeTypeForBinarySignature(imgBytes)); cover.setDescription(""); cover.setPictureType(PictureTypes.DEFAULT_ID); mTag.deleteArtworkField(); mTag.setField(cover); } catch (IOException | IllegalArgumentException | FieldDataInvalidException e) { Log.e(LOG_TAG, "Invalid artwork!", e); Toast.makeText(this, R.string.invalid_artwork_provided, Toast.LENGTH_SHORT).show(); } writeFile(); break; } } }
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();/*from w ww .j a v a 2 s . com*/ } 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.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 ww w . j a va 2 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 ww w.j av 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; } }); }