Example usage for android.os ParcelFileDescriptor close

List of usage examples for android.os ParcelFileDescriptor close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Close the ParcelFileDescriptor.

Usage

From source file:com.proalias.awesomestatus.MainActivity.java

private Bitmap getBitmapFromUri(Uri uri) throws IOException {
    ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
    Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
    parcelFileDescriptor.close();
    return image;
}

From source file:com.serenegiant.testmediastore.MediaStorePhotoAdapter.java

private static final Bitmap getImage(ContentResolver cr, long id, int requestWidth, int requestHeight)
        throws FileNotFoundException, IOException {

    Bitmap result = null;// w  ww . j a  v a2  s.c om
    final ParcelFileDescriptor pfd = cr.openFileDescriptor(
            ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id), "r");
    if (pfd != null) {
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            // just decorde to get image size
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor(), null, options);
            // calculate sub-sampling
            options.inSampleSize = calcSampleSize(options, requestWidth, requestHeight);
            options.inJustDecodeBounds = false;
            result = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor(), null, options);
        } finally {
            pfd.close();
        }
    }
    return result;
}

From source file:net.sf.fdshare.RootFileProvider.java

/**
 * {@inheritDoc}/*from  w  w w. j av  a 2 s. co  m*/
 *
 * Note, that cancellation is inherently racy. The caller must close whatever descriptor may be returned regardless.
 */
@Override
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
        throws FileNotFoundException {
    ParcelFileDescriptor result = null;

    try (Closeable cancellation = new ThreadInterrupter(signal)) {
        result = super.openFile(uri, mode);
        return result;
    } catch (IOException ioe) {
        throw new FileNotFoundException(ioe.getMessage());
    } finally {
        if (signal != null && signal.isCanceled()) {
            if (result != null) {
                try {
                    result.close();
                } catch (IOException ignored) {
                }
            }

            // override whatever exception have resulted from interruption
            signal.throwIfCanceled();
        }
    }
}

From source file:com.uphyca.kitkat.storage.ui.MainFragment.java

/**
 * uri???????//ww w .j  av  a  2 s.  c  o m
 * 
 * @param uri
 * @throws IOException
 */
private void alterDocument(Uri uri) throws IOException {
    ParcelFileDescriptor pfd = getActivity().getContentResolver().openFileDescriptor(uri, "w");
    FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
    fileOutputStream.write(("Overwritten by MyCloud at " + System.currentTimeMillis() + "\n").getBytes());
    // Let the document provider know you're done by closing the stream.
    fileOutputStream.close();
    pfd.close();
}

From source file:freed.cam.apis.camera2.modules.VideoModuleApi2.java

private void setRecorderFilePath() {
    if (!appSettingsManager.GetWriteExternal()) {
        mediaRecorder.setOutputFile(recordingFile.getAbsolutePath());
    } else {//from w ww  .j  a  va  2 s.c  om
        Uri uri = Uri.parse(appSettingsManager.GetBaseFolder());
        DocumentFile df = cameraUiWrapper.getActivityInterface().getFreeDcamDocumentFolder();
        DocumentFile wr = df.createFile("*/*", recordingFile.getName());
        ParcelFileDescriptor fileDescriptor = null;
        try {
            fileDescriptor = cameraUiWrapper.getContext().getContentResolver().openFileDescriptor(wr.getUri(),
                    "rw");
            mediaRecorder.setOutputFile(fileDescriptor.getFileDescriptor());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            try {
                fileDescriptor.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

From source file:org.fedorahosted.freeotp.MainActivity.java

private void exportToFile(final Uri uri) {
    new AsyncTask<Void, Void, Void>() {
        @Override//from  w w  w.  j a  v a2s  .  c  om
        protected Void doInBackground(Void... params) {
            try {
                ParcelFileDescriptor pfd = MainActivity.this.getContentResolver().openFileDescriptor(uri, "w");
                FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
                fileOutputStream.write(tokenPersistence.toJSON().getBytes());
                // Let the document provider know you're done by closing the stream.
                fileOutputStream.close();
                pfd.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Toast.makeText(MainActivity.this, R.string.export_succeeded_text, Toast.LENGTH_LONG).show();
        }
    }.execute((Void) null);
}

From source file:freed.viewer.dngconvert.DngConvertingFragment.java

private void convertRawToDng(File file) {
    byte[] data = null;
    try {//from  w w w  . j  a  v a 2 s .  co  m
        data = RawToDng.readFile(file);
        Log.d("Main", "Filesize: " + data.length + " File:" + file.getAbsolutePath());

    } catch (IOException ex) {
        ex.printStackTrace();
    }
    String out = null;
    if (file.getName().endsWith(FileEnding.RAW))
        out = file.getAbsolutePath().replace(FileEnding.RAW, FileEnding.DNG);
    if (file.getName().endsWith(FileEnding.BAYER))
        out = file.getAbsolutePath().replace(FileEnding.BAYER, FileEnding.DNG);
    RawToDng dng = RawToDng.GetInstance();
    String intsd = StringUtils.GetInternalSDCARD();
    if (VERSION.SDK_INT <= VERSION_CODES.LOLLIPOP || file.getAbsolutePath().contains(intsd))
        dng.setBayerData(data, out);
    else {
        DocumentFile df = ((ActivityInterface) getActivity()).getFreeDcamDocumentFolder();
        DocumentFile wr = df.createFile("image/dng", file.getName().replace(FileEnding.JPG, FileEnding.DNG));
        ParcelFileDescriptor pfd = null;
        try {

            pfd = getContext().getContentResolver().openFileDescriptor(wr.getUri(), "rw");
        } catch (FileNotFoundException | IllegalArgumentException ex) {
            ex.printStackTrace();
        }
        if (pfd != null) {
            dng.SetBayerDataFD(data, pfd, file.getName());
            try {
                pfd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            pfd = null;
        }
    }
    dng.setExifData(100, 0, 0, 0, 0, "", "0", 0);
    if (fakeGPS.isChecked())
        dng.SetGpsData(Altitude, Latitude, Longitude, Provider, gpsTime);
    dng.WriteDngWithProfile(dngprofile);
    data = null;
    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(Uri.fromFile(file));
    getActivity().sendBroadcast(intent);
    if (filesToConvert.length == 1) {

        final Bitmap map = new RawUtils().UnPackRAW(out);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                imageView.setImageBitmap(map);
            }
        });
    }
}

From source file:com.ultramegasoft.flavordex2.util.PhotoUtils.java

/**
 * Load a Bitmap from an image file.//from   ww  w . j  a  va 2 s  . c  o  m
 *
 * @param context   The Context
 * @param uri       The Uri to the image file
 * @param reqWidth  The requested width of the decoded Bitmap
 * @param reqHeight The requested height of the decoded Bitmap
 * @return A Bitmap
 */
@Nullable
public static Bitmap loadBitmap(@NonNull Context context, @NonNull Uri uri, int reqWidth, int reqHeight) {
    final ContentResolver cr = context.getContentResolver();
    try {
        final ParcelFileDescriptor parcelFileDescriptor = cr.openFileDescriptor(uri, "r");
        if (parcelFileDescriptor == null) {
            Log.w(TAG, "Unable to open " + uri.toString());
            return null;
        }
        try {
            final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            final Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(fileDescriptor, null, opts);

            opts.inSampleSize = calculateInSampleSize(opts, reqWidth, reqHeight);
            opts.inJustDecodeBounds = false;

            final Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, opts);
            if ("image/jpeg".equals(opts.outMimeType)) {
                return rotatePhoto(context, uri, bitmap);
            }
            return bitmap;
        } catch (OutOfMemoryError e) {
            Log.e(TAG, "Out of memory", e);
        } finally {
            parcelFileDescriptor.close();
        }
    } catch (FileNotFoundException e) {
        Log.w(TAG, "File not found: " + uri.toString());
    } catch (SecurityException e) {
        Log.w(TAG, "Permission denied for Uri: " + uri.toString());
    } catch (IOException e) {
        Log.e(TAG, "Failed to load bitmap", e);
    }
    return null;
}

From source file:Main.java

public 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//from   ww  w.  j  av  a 2  s. c  o  m
    // used to display this drawable. Take it into account now, so we don't
    // have to
    // scale later.
    w -= 1;
    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:uno.weichen.abnd10_inventoryapp.DetailActivity.java

private Bitmap getBitmapFromUri(Uri uri) {
    ParcelFileDescriptor parcelFileDescriptor = null;
    try {//ww w.  jav a  2s.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));
        }
    }
}