Example usage for android.content ContentResolver openFileDescriptor

List of usage examples for android.content ContentResolver openFileDescriptor

Introduction

In this page you can find the example usage for android.content ContentResolver openFileDescriptor.

Prototype

public final @Nullable ParcelFileDescriptor openFileDescriptor(@NonNull Uri uri, @NonNull String mode)
        throws FileNotFoundException 

Source Link

Document

Open a raw file descriptor to access data under a URI.

Usage

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;/* ww  w . j a v a  2  s.  co  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: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;
    }//from w  w  w.j a  v  a 2s  .  c  om

    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;
    }// ww w  .j  a  va 2  s.com

    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;
    }
}

From source file:org.camlistore.UploadService.java

ParcelFileDescriptor getFileDescriptor(Uri uri) {
    ContentResolver cr = getContentResolver();
    try {/*w w  w .j av  a  2  s  .c om*/
        return cr.openFileDescriptor(uri, "r");
    } catch (FileNotFoundException e) {
        Log.w(TAG, "FileNotFound in getFileDescriptor() for " + uri);
        return null;
    }
}

From source file:com.android.messaging.datamodel.BugleDatabaseOperations.java

/**
 * Read all the parts for a message//from  w w  w  .  jav  a2 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.android.mail.compose.ComposeActivity.java

/**
 * Opens {@link ParcelFileDescriptor} for each of the attachments.  This method must be
 * called before the ComposeActivity finishes.
 * Note: The caller is responsible for closing these file descriptors.
 *///from  w  ww. j av  a 2s. c  o m
private static Bundle initializeAttachmentFds(final Context context, final List<Attachment> attachments) {
    if (attachments == null || attachments.size() == 0) {
        return null;
    }

    final Bundle result = new Bundle(attachments.size());
    final ContentResolver resolver = context.getContentResolver();

    for (Attachment attachment : attachments) {
        if (attachment == null || Utils.isEmpty(attachment.contentUri)) {
            continue;
        }

        ParcelFileDescriptor fileDescriptor;
        try {
            fileDescriptor = resolver.openFileDescriptor(attachment.contentUri, "r");
        } catch (FileNotFoundException e) {
            LogUtils.e(LOG_TAG, e, "Exception attempting to open attachment");
            fileDescriptor = null;
        } catch (SecurityException e) {
            // We have encountered a security exception when attempting to open the file
            // specified by the content uri.  If the attachment has been cached, this
            // isn't a problem, as even through the original permission may have been
            // revoked, we have cached the file.  This will happen when saving/sending
            // a previously saved draft.
            // TODO(markwei): Expose whether the attachment has been cached through the
            // attachment object.  This would allow us to limit when the log is made, as
            // if the attachment has been cached, this really isn't an error
            LogUtils.e(LOG_TAG, e, "Security Exception attempting to open attachment");
            // Just set the file descriptor to null, as the underlying provider needs
            // to handle the file descriptor not being set.
            fileDescriptor = null;
        }

        if (fileDescriptor != null) {
            result.putParcelable(attachment.contentUri.toString(), fileDescriptor);
        }
    }

    return result;
}