Example usage for android.os ParcelFileDescriptor open

List of usage examples for android.os ParcelFileDescriptor open

Introduction

In this page you can find the example usage for android.os ParcelFileDescriptor open.

Prototype

public static ParcelFileDescriptor open(File file, int mode) throws FileNotFoundException 

Source Link

Document

Create a new ParcelFileDescriptor accessing a given file.

Usage

From source file:com.facebook.Request.java

/**
 * Creates a new Request configured to upload a photo to the user's default photo album. The photo
 * will be read from the specified file descriptor.
 *
 * @param session  the Session to use, or null; if non-null, the session must be in an opened state
 * @param file     the file to upload/*from   w  w w  .j  a v a 2 s.co  m*/
 * @param callback a callback that will be called when the request is completed to handle success or error conditions
 * @return a Request that is ready to execute
 */
public static Request newUploadVideoRequest(Session session, File file, Callback callback)
        throws FileNotFoundException {
    ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    Bundle parameters = new Bundle(1);
    parameters.putParcelable(file.getName(), descriptor);

    return new Request(session, MY_VIDEOS, parameters, HttpMethod.POST, callback);
}

From source file:org.alfresco.mobile.android.application.providers.storage.StorageAccessDocumentsProvider.java

@Override
public AssetFileDescriptor openDocumentThumbnail(String documentId, Point sizeHint, CancellationSignal signal)
        throws FileNotFoundException {
    // Log.v(TAG, "openDocumentThumbnail");
    try {//from  w  ww .j ava  2 s.  c  o  m
        Node currentNode = null;
        EncodedQueryUri cUri = new EncodedQueryUri(documentId);
        if (cUri.type != PREFIX_DOC) {
            return null;
        }
        checkSession(cUri);

        currentNode = retrieveNode(cUri.id);

        // Let's retrieve the thumbnail
        // Store the document inside a temporary folder per account
        File downloadedFile = null;
        if (getContext() != null && currentNode != null && session != null) {
            File folder = AlfrescoStorageManager.getInstance(getContext()).getTempFolder(selectedAccount);
            if (folder != null) {
                downloadedFile = new File(folder, currentNode.getName());
            }
        } else {
            return null;
        }

        // Is Document in cache ?
        if (downloadedFile.exists()
                && currentNode.getModifiedAt().getTimeInMillis() < downloadedFile.lastModified()) {
            // Document available locally
            ParcelFileDescriptor pfd = ParcelFileDescriptor.open(downloadedFile,
                    ParcelFileDescriptor.MODE_READ_ONLY);
            return new AssetFileDescriptor(pfd, 0, downloadedFile.length());
        }

        // Not in cache so let's download the content !
        ContentStream contentStream = session.getServiceRegistry().getDocumentFolderService()
                .getRenditionStream(currentNode, DocumentFolderService.RENDITION_THUMBNAIL);

        // Check ContentStream
        if (contentStream == null || contentStream.getLength() == 0) {
            return null;
        }

        // Store the thumbnail locally
        copyFile(contentStream.getInputStream(), contentStream.getLength(), downloadedFile, signal);

        // Return the fileDescriptor
        if (downloadedFile.exists()) {
            ParcelFileDescriptor pfd = ParcelFileDescriptor.open(downloadedFile,
                    ParcelFileDescriptor.MODE_READ_ONLY);
            return new AssetFileDescriptor(pfd, 0, downloadedFile.length());
        } else {
            return null;
        }
    } catch (Exception e) {
        Log.w(TAG, Log.getStackTraceString(e));
        return null;
    }
}

From source file:com.hippo.content.FileProvider.java

/**
 * By default, FileProvider automatically returns the
 * {@link ParcelFileDescriptor} for a file associated with a <code>content://</code>
 * {@link Uri}. To get the {@link ParcelFileDescriptor}, call
 * {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
 * ContentResolver.openFileDescriptor}.// ww  w . ja v a  2 s .  c om
 *
 * To override this method, you must provide your own subclass of FileProvider.
 *
 * @param uri A content URI associated with a file, as returned by
 * {@link #getUriForFile(Context, String, File) getUriForFile()}.
 * @param mode Access mode for the file. May be "r" for read-only access, "rw" for read and
 * write access, or "rwt" for read and write access that truncates any existing file.
 * @return A new {@link ParcelFileDescriptor} with which you can access the file.
 */
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
    // ContentProvider has already checked granted permissions
    final File file = mStrategy.getFileForUri(uri);
    final int fileMode = modeToMode(mode);
    return ParcelFileDescriptor.open(file, fileMode);
}

From source file:dev.dworks.apps.anexplorer.provider.ExternalStorageProvider.java

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override//from  w w w  .  j  a  v a 2s . c  o m
public ParcelFileDescriptor openDocument(String documentId, String mode, CancellationSignal signal)
        throws FileNotFoundException {
    final File file = getFileForDocId(documentId);
    if (Utils.hasKitKat()) {
        final int pfdMode = ParcelFileDescriptor.parseMode(mode);
        if (pfdMode == ParcelFileDescriptor.MODE_READ_ONLY) {
            return ParcelFileDescriptor.open(file, pfdMode);
        } else {
            try {
                // When finished writing, kick off media scanner
                return ParcelFileDescriptor.open(file, pfdMode, mHandler,
                        new ParcelFileDescriptor.OnCloseListener() {
                            @Override
                            public void onClose(IOException e) {
                                FileUtils.updateMedia(getContext(), file.getPath());
                            }
                        });
            } catch (IOException e) {
                throw new FileNotFoundException("Failed to open for writing: " + e);
            }
        }
    } else {
        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);//ParcelFileDescriptor.parseMode(mode));
    }
}

From source file:de.vanita5.twittnuker.provider.TwidereDataProvider.java

private ParcelFileDescriptor getCachedImageFd(final String url) throws FileNotFoundException {
    if (Utils.isDebugBuild()) {
        Log.d(LOGTAG, String.format("getCachedImageFd(%s)", url));
    }//from  ww w. j  a v  a2  s .  co m
    final File file = mImagePreloader.getCachedImageFile(url);
    if (file == null)
        return null;
    return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}

From source file:de.vanita5.twittnuker.provider.TwidereDataProvider.java

private ParcelFileDescriptor getCacheFileFd(final String name) throws FileNotFoundException {
    if (name == null)
        return null;
    final Context mContext = getContext();
    final File cacheDir = mContext.getCacheDir();
    final File file = new File(cacheDir, name);
    if (!file.exists())
        return null;
    return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

/**
 * Creates a new Request configured to upload a photo to the specified graph path. The
 * photo will be read from the specified file.
 *
 * @param graphPath   the graph path to use
 * @param accessToken the access token to use, or null
 * @param file        the file containing the photo to upload
 * @param caption     the user generated caption for the photo.
 * @param params      the parameters// w w w  .j a  v  a2 s . c o m
 * @param callback    a callback that will be called when the request is completed to handle
 *                    success or error conditions
 * @return a Request that is ready to execute
 * @throws java.io.FileNotFoundException
 */
public static GraphRequest newUploadPhotoRequest(String graphPath, AccessToken accessToken, File file,
        String caption, Bundle params, Callback callback) throws FileNotFoundException {
    ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    Bundle parameters = new Bundle();
    if (params != null) {
        parameters.putAll(params);
    }
    parameters.putParcelable(PICTURE_PARAM, descriptor);
    if (caption != null && !caption.isEmpty()) {
        parameters.putString(CAPTION_PARAM, caption);
    }

    return new GraphRequest(accessToken, graphPath, parameters, HttpMethod.POST, callback);
}

From source file:com.groundupworks.wings.facebook.FacebookEndpoint.java

@Override
public Set<ShareNotification> processShareRequests() {
    Set<ShareNotification> notifications = new HashSet<ShareNotification>();

    // Get params associated with the linked account.
    FacebookSettings settings = fetchSettings();
    if (settings != null) {
        // Get share requests for Facebook.
        int destinationId = settings.getDestinationId();
        Destination destination = new Destination(destinationId, ENDPOINT_ID);
        List<ShareRequest> shareRequests = mDatabase.checkoutShareRequests(destination);
        int shared = 0;
        String intentUri = null;/*from   w ww  .  j av  a  2 s  .c o  m*/

        if (!shareRequests.isEmpty()) {
            // Try open session with cached access token.
            Session session = Session.openActiveSessionFromCache(mContext);
            if (session != null && session.isOpened()) {
                // Process share requests.
                for (ShareRequest shareRequest : shareRequests) {
                    File file = new File(shareRequest.getFilePath());
                    ParcelFileDescriptor fileDescriptor = null;
                    try {
                        // Construct graph params.
                        fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
                        Bundle params = new Bundle();
                        params.putParcelable(SHARE_KEY_PICTURE, fileDescriptor);

                        String pageAccessToken = settings.optPageAccessToken();
                        if (DestinationId.PAGE == destinationId && !TextUtils.isEmpty(pageAccessToken)) {
                            params.putString(SHARE_KEY_PAGE_ACCESS_TOKEN, pageAccessToken);
                        }

                        String photoPrivacy = settings.optPhotoPrivacy();
                        if (!TextUtils.isEmpty(photoPrivacy)) {
                            params.putString(SHARE_KEY_PHOTO_PRIVACY, photoPrivacy);
                        }

                        // Execute upload request synchronously. Need to use RequestBatch to set connection timeout.
                        Request request = new Request(session, settings.getAlbumGraphPath(), params,
                                HttpMethod.POST, null);
                        RequestBatch requestBatch = new RequestBatch(request);
                        requestBatch.setTimeout(HTTP_REQUEST_TIMEOUT);
                        List<Response> responses = requestBatch.executeAndWait();
                        if (responses != null && !responses.isEmpty()) {
                            // Process response.
                            Response response = responses.get(0);
                            if (response != null) {
                                FacebookRequestError error = response.getError();
                                if (error == null) {
                                    // Mark as successfully processed.
                                    mDatabase.markSuccessful(shareRequest.getId());

                                    // Parse photo id to construct notification intent uri.
                                    if (intentUri == null) {
                                        String photoId = parsePhotoId(response.getGraphObject());
                                        if (photoId != null && photoId.length() > 0) {
                                            intentUri = SHARE_NOTIFICATION_INTENT_BASE_URI + photoId;
                                        }
                                    }

                                    shared++;
                                } else {
                                    mDatabase.markFailed(shareRequest.getId());

                                    Category category = error.getCategory();
                                    if (Category.AUTHENTICATION_RETRY.equals(category)
                                            || Category.PERMISSION.equals(category)) {
                                        // Update account linking state to unlinked.
                                        unlink();
                                    }
                                }
                            } else {
                                mDatabase.markFailed(shareRequest.getId());
                            }
                        } else {
                            mDatabase.markFailed(shareRequest.getId());
                        }
                    } catch (FacebookException e) {
                        mDatabase.markFailed(shareRequest.getId());
                    } catch (IllegalArgumentException e) {
                        mDatabase.markFailed(shareRequest.getId());
                    } catch (FileNotFoundException e) {
                        mDatabase.markFailed(shareRequest.getId());
                    } catch (Exception e) {
                        // Safety.
                        mDatabase.markFailed(shareRequest.getId());
                    } finally {
                        if (fileDescriptor != null) {
                            try {
                                fileDescriptor.close();
                            } catch (IOException e) {
                                // Do nothing.
                            }
                        }
                    }
                }
            } else {
                // Mark all share requests as failed to process since we failed to open an active session.
                for (ShareRequest shareRequest : shareRequests) {
                    mDatabase.markFailed(shareRequest.getId());
                }
            }
        }

        // Construct and add notification representing share results.
        if (shared > 0) {
            notifications.add(new FacebookShareNotification(mContext, destination.getHash(),
                    settings.getAlbumName(), shared, intentUri));
        }
    }

    return notifications;
}

From source file:com.facebook.Request.java

/**
 * Creates a new Request configured to upload an image to create a staging resource. Staging resources
 * allow you to post binary data such as images, in preparation for a post of an Open Graph object or action
 * which references the image. The URI returned when uploading a staging resource may be passed as the image
 * property for an Open Graph object or action.
 *
 * @param session//from  w ww. ja  v a 2s. co m
 *            the Session to use, or null; if non-null, the session must be in an opened state
 * @param file
 *            the file containing the image to upload
 * @param callback
 *            a callback that will be called when the request is completed to handle success or error conditions
 * @return a Request that is ready to execute
 */
public static Request newUploadStagingResourceWithImageRequest(Session session, File file, Callback callback)
        throws FileNotFoundException {
    ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    ParcelFileDescriptorWithMimeType descriptorWithMimeType = new ParcelFileDescriptorWithMimeType(descriptor,
            "image/png");
    Bundle parameters = new Bundle(1);
    parameters.putParcelable(STAGING_PARAM, descriptorWithMimeType);

    return new Request(session, MY_STAGING_RESOURCES, parameters, HttpMethod.POST, callback);
}