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:org.odk.collect.android.utilities.MediaUtils.java

private static File getGoogleDriveFile(Context context, Uri uri) throws GDriveConnectionException {
    if (!Collect.getInstance().isNetworkAvailable()) {
        throw new GDriveConnectionException();
    }// ww w .  ja  v a2s .  com
    if (uri == null) {
        return null;
    }
    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    String filePath = new File(context.getCacheDir(), "tmp").getAbsolutePath();
    try {
        ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");
        if (parcelFileDescriptor == null) {
            return null;
        }
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        inputStream = new FileInputStream(fileDescriptor);
        outputStream = new FileOutputStream(filePath);
        int read;
        byte[] bytes = new byte[4096];
        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        return new File(filePath);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
    return null;
}

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

/**
 * Load a Bitmap from an image file./*  w ww  .  j  a va  2s.  co  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:com.jaspersoft.android.jaspermobile.domain.interactor.report.GetPrintReportPageCase.java

@Override
protected Observable<ParcelFileDescriptor> buildUseCaseObservable(final PrintRequest request) {
    final PageRequest pageRequest = request.getPageRequest();
    return mReportRepository.getReport(pageRequest.getUri())
            .flatMap(new Func1<RxReportExecution, Observable<ReportPage>>() {
                @Override//w  ww  .  j  av  a 2 s. c  om
                public Observable<ReportPage> call(RxReportExecution execution) {
                    return mReportPageRepository.get(execution, pageRequest);
                }
            }).flatMap(new Func1<ReportPage, Observable<ParcelFileDescriptor>>() {
                @Override
                public Observable<ParcelFileDescriptor> call(ReportPage page) {
                    ParcelFileDescriptor destination = request.getDestination();
                    OutputStream output = new FileOutputStream(destination.getFileDescriptor());
                    InputStream stream = new ByteArrayInputStream(page.getContent());
                    try {
                        IOUtils.copy(stream, output);
                    } catch (IOException e) {
                        return Observable.error(e);
                    }
                    IOUtils.closeQuietly(stream);

                    return Observable.just(destination);
                }
            });
}

From source file:com.maskyn.fileeditorpro.task.SaveFileTask.java

private void writeUri(Uri uri, String newContent, String encoding) throws IOException {
    ParcelFileDescriptor pfd = activity.getContentResolver().openFileDescriptor(uri, "w");
    FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
    fileOutputStream.write(newContent.getBytes(Charset.forName(encoding)));
    fileOutputStream.close();/* ww  w. j  av a  2 s.c om*/
    pfd.close();
}

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;/*from  w  w w  . j  a v a  2  s . c  o  m*/
    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:com.renard.ocr.help.OCRLanguageInstallService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (!intent.hasExtra(DownloadManager.EXTRA_DOWNLOAD_ID)) {
        return;//from   w ww.j a  v a2 s . c  om
    }
    final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
    if (downloadId != 0) {

        DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        ParcelFileDescriptor file;
        try {
            file = dm.openDownloadedFile(downloadId);
            FileInputStream fin = new FileInputStream(file.getFileDescriptor());
            BufferedInputStream in = new BufferedInputStream(fin);
            FileOutputStream out = openFileOutput("tess-lang.tmp", Context.MODE_PRIVATE);
            GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
            final byte[] buffer = new byte[2048 * 2];
            int n = 0;
            while (-1 != (n = gzIn.read(buffer))) {
                out.write(buffer, 0, n);
            }
            out.close();
            gzIn.close();
            FileInputStream fileIn = openFileInput("tess-lang.tmp");
            TarArchiveInputStream tarIn = new TarArchiveInputStream(fileIn);

            TarArchiveEntry entry = tarIn.getNextTarEntry();

            while (entry != null && !(entry.getName().endsWith(".traineddata")
                    && !entry.getName().endsWith("_old.traineddata"))) {
                entry = tarIn.getNextTarEntry();
            }
            if (entry != null) {
                File tessDir = Util.getTrainingDataDir(this);
                final String langName = entry.getName().substring("tesseract-ocr/tessdata/".length());
                File trainedData = new File(tessDir, langName);
                FileOutputStream fout = new FileOutputStream(trainedData);
                int len;
                while ((len = tarIn.read(buffer)) != -1) {
                    fout.write(buffer, 0, len);
                }
                fout.close();
                String lang = langName.substring(0, langName.length() - ".traineddata".length());
                notifyReceivers(lang);
            }
            tarIn.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            String tessDir = Util.getTessDir(this);
            File targetFile = new File(tessDir, OCRLanguageActivity.DOWNLOADED_TRAINING_DATA);
            if (targetFile.exists()) {
                targetFile.delete();
            }
        }

    }
}

From source file:com.csipsimple.backup.SipProfilesHelper.java

@Override
public void writeNewStateDescription(ParcelFileDescriptor newState) {
    long fileModified = databaseFile.lastModified();
    try {/*from   w  w w.  j a va2  s .co  m*/
        FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor());
        DataOutputStream out = new DataOutputStream(outstream);
        out.writeLong(fileModified);
        out.close();
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage final local backup state", e);
    }
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MusicUtils.java

private static Bitmap getArtworkFromFile(Context context, long songid, long albumid) {
    Bitmap bm = null;/*from   ww  w . j a  v a  2 s .co  m*/
    byte[] art = null;
    String path = null;

    if (albumid < 0 && songid < 0) {
        throw new IllegalArgumentException("Must specify an album or a song id");
    }

    try {
        if (albumid < 0) {
            Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
            ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
            if (pfd != null) {
                FileDescriptor fd = pfd.getFileDescriptor();
                bm = BitmapFactory.decodeFileDescriptor(fd);
            }
        } else {
            Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid);
            ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
            if (pfd != null) {
                FileDescriptor fd = pfd.getFileDescriptor();
                bm = BitmapFactory.decodeFileDescriptor(fd);
            }
        }
    } catch (IllegalStateException | FileNotFoundException ex) {
    }
    if (bm != null) {
        mCachedBit = bm;
    }
    return bm;
}

From source file:com.github.barteksc.pdfviewpager.adapter.PDFPagerAdapter.java

protected FileDescriptor getSeekableFileDescriptor(String path) throws IOException {
    ParcelFileDescriptor pfd;

    File pdfCopy = new File(path);
    if (pdfCopy.exists()) {
        pfd = ParcelFileDescriptor.open(pdfCopy, ParcelFileDescriptor.MODE_READ_ONLY);
        return pfd.getFileDescriptor();
    }/*  w ww  .j ava 2 s  . c  o m*/

    if (isAnAsset(path)) {
        pdfCopy = new File(context.getCacheDir(), path);
        pfd = ParcelFileDescriptor.open(pdfCopy, ParcelFileDescriptor.MODE_READ_ONLY);
    } else {
        URI uri = URI.create(String.format("file://%s", path));
        pfd = context.getContentResolver().openFileDescriptor(Uri.parse(uri.toString()), "rw");
    }

    if (pfd == null) {
        throw new IOException("Cannot get FileDescriptor for " + path);
    }

    return pfd.getFileDescriptor();
}

From source file:com.csipsimple.backup.SipSharedPreferencesHelper.java

@Override
public void writeNewStateDescription(ParcelFileDescriptor newState) {
    long fileModified = 0;
    if (prefsFiles != null) {
        prefsFiles.lastModified();/* w  w  w  .j a v  a 2 s  .  c o  m*/
    }
    try {
        FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor());
        DataOutputStream out = new DataOutputStream(outstream);
        out.writeLong(fileModified);
        out.close();
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage final local backup state", e);
    }
}