Example usage for android.os ParcelFileDescriptor getFileDescriptor

List of usage examples for android.os ParcelFileDescriptor getFileDescriptor

Introduction

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

Prototype

public FileDescriptor getFileDescriptor() 

Source Link

Document

Retrieve the actual FileDescriptor associated with this object.

Usage

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 2s  . 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.gecq.musicwave.cache.ImageCache.java

/**
 * Used to fetch the artwork for an album locally from the user's device
 *
 * @param context The {@link Context} to use
 * @param albumID The ID of the album to find artwork for
 * @return The artwork for an album//from w w  w  .j  av  a2 s .co  m
 */
public final Bitmap getArtworkFromFile(final Context context, final long albumId) {
    if (albumId < 0) {
        return null;
    }
    Bitmap artwork = null;
    waitUntilUnpaused();
    try {
        final Uri uri = ContentUris.withAppendedId(mArtworkUri, albumId);
        final ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri,
                "r");
        if (parcelFileDescriptor != null) {
            final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            artwork = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        }
    } catch (final IllegalStateException e) {
        // Log.e(TAG, "IllegalStateExcetpion - getArtworkFromFile - ", e);
    } catch (final FileNotFoundException e) {
        // Log.e(TAG, "FileNotFoundException - getArtworkFromFile - ", e);
    } catch (final OutOfMemoryError evict) {
        // Log.e(TAG, "OutOfMemoryError - getArtworkFromFile - ", evict);
        evictAll();
    }
    return artwork;
}

From source file:com.andrew.apollo.cache.ImageCache.java

/**
 * Used to fetch the artwork for an album locally from the user's device
 * /* www  .jav  a  2  s .  c  o  m*/
 * @param context The {@link Context} to use
 * @param albumID The ID of the album to find artwork for
 * @return The artwork for an album
 */
public final Bitmap getArtworkFromFile(final Context context, final String albumId) {
    if (TextUtils.isEmpty(albumId)) {
        return null;
    }
    Bitmap artwork = null;
    while (mPauseDiskAccess) {
        // Pause for a moment
    }
    try {
        final Uri uri = ContentUris.withAppendedId(mArtworkUri, Long.valueOf(albumId));
        final ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri,
                "r");
        if (parcelFileDescriptor != null) {
            final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            artwork = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        }
    } catch (final IllegalStateException e) {
        // Log.e(TAG, "IllegalStateExcetpion - getArtworkFromFile - ", e);
    } catch (final FileNotFoundException e) {
        // Log.e(TAG, "FileNotFoundException - getArtworkFromFile - ", e);
    } catch (final OutOfMemoryError evict) {
        // Log.e(TAG, "OutOfMemoryError - getArtworkFromFile - ", evict);
        evictAll();
    }
    return artwork;
}

From source file:com.boko.vimusic.cache.ImageCache.java

/**
 * Used to fetch the artwork for an album locally from the user's device
 * //from   ww  w . j  a  v  a  2s.  c  o  m
 * @param context
 *            The {@link Context} to use
 * @param albumID
 *            The ID of the album to find artwork for
 * @return The artwork for an album
 */
public final Bitmap getArtworkFromFile(final Context context, final String albumId) {
    if (albumId == null) {
        return null;
    }
    Bitmap artwork = null;
    waitUntilUnpaused();
    try {
        final Uri uri = ContentUris.withAppendedId(mArtworkUri, Long.valueOf(albumId));
        final ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri,
                "r");
        if (parcelFileDescriptor != null) {
            final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            artwork = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        }
    } catch (final IllegalStateException e) {
        // Log.e(TAG, "IllegalStateExcetpion - getArtworkFromFile - ", e);
    } catch (final FileNotFoundException e) {
        // Log.e(TAG, "FileNotFoundException - getArtworkFromFile - ", e);
    } catch (final OutOfMemoryError evict) {
        // Log.e(TAG, "OutOfMemoryError - getArtworkFromFile - ", evict);
        evictAll();
    }
    return artwork;
}

From source file:com.kanedias.vanilla.audiotag.PluginService.java

/**
 * Write changes through SAF framework - the only way to do it in Android > 4.4 when working with SD card
 * @param activityResponse response with URI contained in. Can be null if tree permission is already given.
 *//*from  w  w  w  . j a v a  2 s.  co  m*/
private void persistThroughSaf(Intent activityResponse) {
    Uri safUri;
    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 using now Document API

        // /storage/volume/Music/some.mp3 will become [storage, volume, music, some.mp3]
        List<String> pathSegments = new ArrayList<>(
                Arrays.asList(mAudioFile.getFile().getAbsolutePath().split("/")));
        Uri allowedSdRoot = Uri.parse(mPrefs.getString(PREF_SDCARD_URI, ""));
        safUri = findInDocumentTree(DocumentFile.fromTreeUri(this, allowedSdRoot), pathSegments);
    } else {
        Intent originalSafResponse = activityResponse.getParcelableExtra(EXTRA_PARAM_SAF_P2P);
        safUri = originalSafResponse.getData();
    }

    if (safUri == null) {
        // nothing selected or invalid file?
        Toast.makeText(this, R.string.saf_nothing_selected, Toast.LENGTH_LONG).show();
        return;
    }

    try {
        // we don't have fd-related audiotagger write functions, have to use workaround
        // write audio file to temp cache dir
        // jaudiotagger can't work through file descriptor, sadly
        File original = mAudioFile.getFile();
        File temp = File.createTempFile("tmp-media", '.' + Utils.getExtension(original));
        Utils.copy(original, temp); // jtagger writes only header, we should copy the rest
        temp.deleteOnExit(); // in case of exception it will be deleted too
        mAudioFile.setFile(temp);
        AudioFileIO.write(mAudioFile);

        // retrieve FD from SAF URI
        ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(safUri, "rw");
        if (pfd == null) {
            // should not happen
            Log.e(LOG_TAG, "SAF provided incorrect URI!" + safUri);
            return;
        }

        // now read persisted data and write it to real FD provided by SAF
        FileInputStream fis = new FileInputStream(temp);
        byte[] audioContent = TagEditorUtils.readFully(fis);
        FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
        fos.write(audioContent);
        fos.close();

        // delete temporary file used
        temp.delete();

        // rescan original file
        MediaScannerConnection.scanFile(this, new String[] { original.getAbsolutePath() }, null, null);
        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:us.theparamountgroup.android.inventory.EditorActivity.java

private Bitmap getBitmapFromUri(Uri uri) {
    if (uri == null) {
        return null;
    }/* w w w . j a  va 2 s.  c o m*/
    int targetW = mImageView.getWidth();
    int targetH = mImageView.getHeight();
    ParcelFileDescriptor parcelFileDescriptor = null;
    try {
        parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fileDescriptor, null, opts);
        int photoW = opts.outWidth;
        int photoH = opts.outHeight;

        int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

        opts.inJustDecodeBounds = false;
        opts.inSampleSize = scaleFactor;
        opts.inPurgeable = true;
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, opts);
        return image;

    } catch (Exception e) {
        Log.e(LOG_TAG, "Failed to load image.", e);
        return null;
    } finally {
        try {
            if (parcelFileDescriptor != null) {
                parcelFileDescriptor.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(LOG_TAG, "Error closing ParcelFile Descriptor");
        }
    }
}

From source file:net.gsantner.opoc.util.ShareUtil.java

/**
 * Extract result data from {@link Activity#onActivityResult(int, int, Intent)}.
 * Forward all arguments from activity. Only requestCodes from {@link ShareUtil} get analyzed.
 * Also may forward results via local broadcast
 *///from w  w w. ja v  a 2  s  . c o m
public Object extractResultFromActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case REQUEST_CAMERA_PICTURE: {
        String picturePath = (resultCode == RESULT_OK) ? _lastCameraPictureFilepath : null;
        if (picturePath != null) {
            sendLocalBroadcastWithStringExtra(REQUEST_CAMERA_PICTURE + "", EXTRA_FILEPATH, picturePath);
        }
        return picturePath;
    }
    case REQUEST_PICK_PICTURE: {
        if (resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            String picturePath = null;

            Cursor cursor = _context.getContentResolver().query(selectedImage, filePathColumn, null, null,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                for (String column : filePathColumn) {
                    int curColIndex = cursor.getColumnIndex(column);
                    if (curColIndex == -1) {
                        continue;
                    }
                    picturePath = cursor.getString(curColIndex);
                    if (!TextUtils.isEmpty(picturePath)) {
                        break;
                    }
                }
                cursor.close();
            }

            // Retrieve image from file descriptor / Cloud, e.g.: Google Drive, Picasa
            if (picturePath == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                try {
                    ParcelFileDescriptor parcelFileDescriptor = _context.getContentResolver()
                            .openFileDescriptor(selectedImage, "r");
                    if (parcelFileDescriptor != null) {
                        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                        FileInputStream input = new FileInputStream(fileDescriptor);

                        // Create temporary file in cache directory
                        picturePath = File.createTempFile("image", "tmp", _context.getCacheDir())
                                .getAbsolutePath();
                        FileUtils.writeFile(new File(picturePath), FileUtils.readCloseBinaryStream(input));
                    }
                } catch (IOException ignored) {
                    // nothing we can do here, null value will be handled below
                }
            }

            // Return path to picture on success, else null
            if (picturePath != null) {
                sendLocalBroadcastWithStringExtra(REQUEST_CAMERA_PICTURE + "", EXTRA_FILEPATH, picturePath);
            }
            return picturePath;
        }
        break;
    }
    }
    return null;
}

From source file:com.example.android.vault.EncryptedDocument.java

/**
 * Encrypt and write both the metadata and content sections of this
 * document, reading the content from the given pipe. Internally uses
 * {@link ParcelFileDescriptor#checkError()} to verify that content arrives
 * without errors. Writes to temporary file to keep atomic view of contents,
 * swapping into place only when write is successful.
 * <p/>/*  w ww.j  a va  2 s.  c o m*/
 * Pipe is left open, so caller is responsible for calling
 * {@link ParcelFileDescriptor#close()} or
 * {@link ParcelFileDescriptor#closeWithError(String)}.
 *
 * @param contentIn read end of a pipe.
 */
public void writeMetadataAndContent(JSONObject meta, ParcelFileDescriptor contentIn)
        throws IOException, GeneralSecurityException {
    // Write into temporary file to provide an atomic view of existing
    // contents during write, and also to recover from failed writes.
    final String tempName = mFile.getName() + ".tmp_" + Thread.currentThread().getId();
    final File tempFile = new File(mFile.getParentFile(), tempName);

    RandomAccessFile f = new RandomAccessFile(tempFile, "rw");
    try {
        // Truncate any existing data
        f.setLength(0);

        // Write content first to detect size
        if (contentIn != null) {
            f.seek(CONTENT_OFFSET);
            final int plainLength = writeSection(f, new FileInputStream(contentIn.getFileDescriptor()));
            meta.put(Document.COLUMN_SIZE, plainLength);

            // Verify that remote side of pipe finished okay; if they
            // crashed or indicated an error then this throws and we
            // leave the original file intact and clean up temp below.
            contentIn.checkError();
        }

        meta.put(Document.COLUMN_DOCUMENT_ID, mDocId);
        meta.put(Document.COLUMN_LAST_MODIFIED, System.currentTimeMillis());

        // Rewind and write metadata section
        f.seek(0);
        f.writeInt(MAGIC_NUMBER);

        final ByteArrayInputStream metaIn = new ByteArrayInputStream(
                meta.toString().getBytes(StandardCharsets.UTF_8));
        writeSection(f, metaIn);

        if (f.getFilePointer() > CONTENT_OFFSET) {
            throw new IOException("Metadata section was too large");
        }

        // Everything written fine, atomically swap new data into place.
        // fsync() before close would be overkill, since rename() is an
        // atomic barrier.
        f.close();
        tempFile.renameTo(mFile);

    } catch (JSONException e) {
        throw new IOException(e);
    } finally {
        // Regardless of what happens, always try cleaning up.
        f.close();
        tempFile.delete();
    }
}

From source file:com.netcompss.ffmpeg4android_client.BaseVideo.java

public String getFileNameByUri(Context context, Uri uri) {
    String fileName = "unknown";// default fileName
    Uri filePathUri = uri;//from   w w  w  .ja v a2 s .  c o 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//  ww w.  j  a  v a  2 s .  c o  m
 * @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;
}