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:Main.java

@Nullable
private static File getFromMediaUriPfd(Context context, ContentResolver resolver, Uri uri) {
    if (uri == null)
        return null;

    FileInputStream input = null;
    FileOutputStream output = null;
    try {//from   www.  j a  va  2s .com
        ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
        FileDescriptor fd = pfd.getFileDescriptor();
        input = new FileInputStream(fd);

        String tempFilename = getTempFilename(context);
        output = new FileOutputStream(tempFilename);

        int read;
        byte[] bytes = new byte[4096];
        while ((read = input.read(bytes)) != -1) {
            output.write(bytes, 0, read);
        }
        return new File(tempFilename);
    } catch (IOException ignored) {
        // Nothing we can do
    } finally {
        closeSilently(input);
        closeSilently(output);
    }
    return null;
}

From source file:Main.java

public static Bitmap getBitmapFromUri(Uri uri, Context context) {
    ParcelFileDescriptor parcelFileDescriptor = null;
    try {/*from w w  w  .  j  av  a2s  .  com*/

        parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return image;
    } catch (Exception e) {
        Log.e(TAG, "Failed to load image.", e);
        return null;
    } finally {
        try {
            if (parcelFileDescriptor != null) {
                parcelFileDescriptor.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "Error closing ParcelFile Descriptor");
        }
    }
}

From source file:Main.java

private static File getFromMediaUriPfd(Context context, ContentResolver resolver, Uri uri) {
    if (uri == null)
        return null;

    FileInputStream input = null;
    FileOutputStream output = null;
    try {/*www . j a v  a  2s  .  c  o  m*/
        ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
        FileDescriptor fd = pfd.getFileDescriptor();
        input = new FileInputStream(fd);

        String tempFilename = getTempFilename(context);
        output = new FileOutputStream(tempFilename);

        int read;
        byte[] bytes = new byte[4096];
        while ((read = input.read(bytes)) != -1) {
            output.write(bytes, 0, read);
        }
        return new File(tempFilename);
    } catch (IOException ignored) {
        // Nothing we can do
    } finally {
        closeSilently(input);
        closeSilently(output);
    }
    return null;
}

From source file:org.anoopam.main.anoopamaudio.UtilFunctions.java

/**
 * Get the album image from albumId/*from   www .  jav  a  2s. c o  m*/
 * @param context
 * @param album_id
 * @return
 */
public static Bitmap getAlbumart(Context context, Long album_id) {
    Bitmap bm = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    try {
        final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
        Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
        ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
        if (pfd != null) {
            FileDescriptor fd = pfd.getFileDescriptor();
            bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
            pfd = null;
            fd = null;
        }
    } catch (Error ee) {
    } catch (Exception e) {
    }
    return bm;
}

From source file:org.andstatus.app.backup.MyBackupDescriptor.java

static MyBackupDescriptor fromEmptyParcelFileDescriptor(ParcelFileDescriptor parcelFileDescriptor,
        ProgressLogger progressLoggerIn) throws IOException {
    MyBackupDescriptor myBackupDescriptor = new MyBackupDescriptor(progressLoggerIn);
    myBackupDescriptor.fileDescriptor = parcelFileDescriptor.getFileDescriptor();
    myBackupDescriptor.backupSchemaVersion = BACKUP_SCHEMA_VERSION;

    PackageManager pm = MyContextHolder.get().context().getPackageManager();
    PackageInfo pi;//w  ww  .j a  va2  s  .  com
    try {
        pi = pm.getPackageInfo(MyContextHolder.get().context().getPackageName(), 0);
    } catch (NameNotFoundException e) {
        throw new IOException(e);
    }
    myBackupDescriptor.applicationVersionCode = pi.versionCode;
    return myBackupDescriptor;
}

From source file:org.andstatus.app.backup.MyBackupDescriptor.java

static MyBackupDescriptor fromOldParcelFileDescriptor(ParcelFileDescriptor parcelFileDescriptor,
        ProgressLogger progressLogger) {
    MyBackupDescriptor myBackupDescriptor = new MyBackupDescriptor(progressLogger);
    if (parcelFileDescriptor != null) {
        myBackupDescriptor.fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        JSONObject jso = FileDescriptorUtils.getJSONObject(parcelFileDescriptor.getFileDescriptor());
        myBackupDescriptor.backupSchemaVersion = jso.optInt(KEY_BACKUP_SCHEMA_VERSION,
                myBackupDescriptor.backupSchemaVersion);
        myBackupDescriptor.createdDate = jso.optLong(KEY_CREATED_DATE, myBackupDescriptor.createdDate);
        myBackupDescriptor.applicationVersionCode = jso.optInt(KEY_APPLICATION_VERSION_CODE,
                myBackupDescriptor.applicationVersionCode);
        myBackupDescriptor.accountsCount = jso.optLong(KEY_ACCOUNTS_COUNT, myBackupDescriptor.accountsCount);
        if (myBackupDescriptor.backupSchemaVersion != BACKUP_SCHEMA_VERSION) {
            try {
                MyLog.w(TAG, "Bad backup descriptor: " + jso.toString(2));
            } catch (JSONException e) {
                MyLog.d(TAG, "Bad backup descriptor: " + jso.toString(), e);
            }/* ww  w  . j  a  v a2 s  .  c  om*/
        }
    }
    return myBackupDescriptor;
}

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  a v  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:com.github.michalbednarski.intentslab.Utils.java

@TargetApi(13) // Function handles all supported api levels
public static InputStream dumpSystemService(Context context, String serviceName, final String[] arguments)
        throws Exception {
    // Check if we have permission to invoke dump from our process
    final boolean canDumpLocally = context.getPackageManager().checkPermission(android.Manifest.permission.DUMP,
            context.getPackageName()) == PackageManager.PERMISSION_GRANTED;

    // On versions without createPipe() just execute dumpsys
    if (android.os.Build.VERSION.SDK_INT < 9) {
        if (!canDumpLocally) {
            throw new Exception("Dumping is not supported on this system version");
        }//from www . jav  a 2  s .  c  o m
        String[] progArray = new String[arguments != null ? 2 + arguments.length : 2];
        progArray[0] = "dumpsys";
        progArray[1] = serviceName;
        if (arguments != null) {
            System.arraycopy(arguments, 0, progArray, 2, arguments.length);
        }
        return Runtime.getRuntime().exec(progArray).getInputStream();
    }

    // Get service
    final Class<?> serviceManager = Class.forName("android.os.ServiceManager");
    final IBinder service = (IBinder) serviceManager.getMethod("getService", String.class).invoke(null,
            serviceName);

    // Check permissions and get remote interface if needed
    IRemoteInterface remoteInterface = null;
    if (!canDumpLocally) {
        remoteInterface = RunAsManager.getRemoteInterfaceForSystemDebuggingCommands();
        if (remoteInterface == null) {
            throw new SecurityException("Process has no permission to dump services");
        }
    }

    // Create pipe, write(pipe[0]) -> read(pipe[1])
    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
    final ParcelFileDescriptor readablePipe = pipe[0];
    final ParcelFileDescriptor writablePipe = pipe[1];

    try {
        // Execute dump
        if (canDumpLocally) {
            if (android.os.Build.VERSION.SDK_INT >= 13) {
                service.dumpAsync(writablePipe.getFileDescriptor(), arguments);
                writablePipe.close();
            } else {
                (new Thread() {
                    @Override
                    public void run() {
                        try {
                            service.dump(writablePipe.getFileDescriptor(), arguments);
                            writablePipe.close();
                        } catch (Exception e) {
                            // TODO: can we handle this?
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else {
            remoteInterface.dumpServiceAsync(service, writablePipe, arguments);
            writablePipe.close();
        }
        // If anything went wrong, close pipe and rethrow
    } catch (Throwable e) {
        readablePipe.close();
        writablePipe.close();
        throwUnchecked(e);
        throw new Error(); // Unreachable
    }

    // Return stream that will ensure closing fd
    return new FileInputStream(readablePipe.getFileDescriptor()) {
        @Override
        public void close() throws IOException {
            super.close();
            readablePipe.close();
        }
    };
}

From source file:com.pavlospt.rxfile.RxFile.java

private static File fileFromUri(Context context, Uri data) throws Exception {
    DocumentFile file = DocumentFile.fromSingleUri(context, data);
    String fileType = file.getType();
    String fileName = file.getName();
    File fileCreated;// w  w w  .ja va 2 s  .  c om
    ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
            Constants.READ_MODE);
    InputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
    logDebug("External cache dir:" + context.getExternalCacheDir());
    String filePath = context.getExternalCacheDir() + Constants.FOLDER_SEPARATOR + fileName;
    String fileExtension = fileName.substring((fileName.lastIndexOf('.')) + 1);
    String mimeType = getMimeType(fileName);

    logDebug("From Google Drive guessed type: " + getMimeType(fileName));

    logDebug("Extension: " + fileExtension);

    if (fileType.equals(Constants.APPLICATION_PDF) && mimeType == null) {
        filePath += "." + Constants.PDF_EXTENSION;
    }

    if (!createFile(filePath)) {
        return new File(filePath);
    }

    ReadableByteChannel from = Channels.newChannel(inputStream);
    WritableByteChannel to = Channels.newChannel(new FileOutputStream(filePath));
    fastChannelCopy(from, to);
    from.close();
    to.close();
    fileCreated = new File(filePath);
    logDebug("Path for made file: " + fileCreated.getAbsolutePath());
    return fileCreated;
}

From source file:com.xxxifan.devbox.library.rxfile.RxFile.java

private static File fileFromUri(Context context, Uri data) throws Exception {
    DocumentFile file = DocumentFile.fromSingleUri(context, data);
    String fileType = file.getType();
    String fileName = file.getName();
    File fileCreated;//from w w w.  j  av  a 2  s  .c  om
    ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data,
            Constants.READ_MODE);
    InputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
    Log.e(TAG, "External cache dir:" + context.getExternalCacheDir());
    String filePath = context.getExternalCacheDir() + Constants.FOLDER_SEPARATOR + fileName;
    String fileExtension = fileName.substring((fileName.lastIndexOf('.')) + 1);
    String mimeType = getMimeType(fileName);

    Log.e(TAG, "From Drive guessed type: " + getMimeType(fileName));

    Log.e(TAG, "Extension: " + fileExtension);

    if (fileType.equals(Constants.APPLICATION_PDF) && mimeType == null) {
        filePath += "." + Constants.PDF_EXTENSION;
    }

    if (!createFile(filePath)) {
        return new File(filePath);
    }

    ReadableByteChannel from = Channels.newChannel(inputStream);
    WritableByteChannel to = Channels.newChannel(new FileOutputStream(filePath));
    fastChannelCopy(from, to);
    from.close();
    to.close();
    fileCreated = new File(filePath);
    Log.e(TAG, "Path for made file: " + fileCreated.getAbsolutePath());
    return fileCreated;
}