Search in sources :

Example 51 with AssetFileDescriptor

use of android.content.res.AssetFileDescriptor in project android_frameworks_base by crdroidandroid.

the class DocumentsContract method openImageThumbnail.

/**
     * Open the given image for thumbnail purposes, using any embedded EXIF
     * thumbnail if available, and providing orientation hints from the parent
     * image.
     *
     * @hide
     */
public static AssetFileDescriptor openImageThumbnail(File file) throws FileNotFoundException {
    final ParcelFileDescriptor pfd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    Bundle extras = null;
    try {
        final ExifInterface exif = new ExifInterface(file.getAbsolutePath());
        switch(exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                extras = new Bundle(1);
                extras.putInt(EXTRA_ORIENTATION, 90);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                extras = new Bundle(1);
                extras.putInt(EXTRA_ORIENTATION, 180);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                extras = new Bundle(1);
                extras.putInt(EXTRA_ORIENTATION, 270);
                break;
        }
        final long[] thumb = exif.getThumbnailRange();
        if (thumb != null) {
            return new AssetFileDescriptor(pfd, thumb[0], thumb[1], extras);
        }
    } catch (IOException e) {
    }
    return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH, extras);
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) Bundle(android.os.Bundle) ExifInterface(android.media.ExifInterface) ParcelFileDescriptor(android.os.ParcelFileDescriptor) IOException(java.io.IOException)

Example 52 with AssetFileDescriptor

use of android.content.res.AssetFileDescriptor in project android_frameworks_base by crdroidandroid.

the class TestDocumentsProvider method openDocumentThumbnail.

@Override
public AssetFileDescriptor openDocumentThumbnail(String docId, Point sizeHint, CancellationSignal signal) throws FileNotFoundException {
    if (LAG)
        lagUntilCanceled(signal);
    if (THUMB_WEDGE)
        wedgeUntilCanceled(signal);
    if (THUMB_CRASH)
        System.exit(12);
    final Bitmap bitmap = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(bitmap);
    final Paint paint = new Paint();
    paint.setColor(Color.BLUE);
    canvas.drawColor(Color.RED);
    canvas.drawLine(0, 0, 32, 32, paint);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 50, bos);
    final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    try {
        final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createReliablePipe();
        new AsyncTask<Object, Object, Object>() {

            @Override
            protected Object doInBackground(Object... params) {
                final FileOutputStream fos = new FileOutputStream(fds[1].getFileDescriptor());
                try {
                    Streams.copy(bis, fos);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                IoUtils.closeQuietly(fds[1]);
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        return new AssetFileDescriptor(fds[0], 0, AssetFileDescriptor.UNKNOWN_LENGTH);
    } catch (IOException e) {
        throw new FileNotFoundException(e.getMessage());
    }
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) Canvas(android.graphics.Canvas) FileNotFoundException(java.io.FileNotFoundException) Paint(android.graphics.Paint) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Bitmap(android.graphics.Bitmap) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) ParcelFileDescriptor(android.os.ParcelFileDescriptor)

Example 53 with AssetFileDescriptor

use of android.content.res.AssetFileDescriptor in project android_frameworks_base by AOSPA.

the class MediaMetadataRetriever method setDataSource.

/**
     * Sets the data source as a content Uri. Call this method before 
     * the rest of the methods in this class. This method may be time-consuming.
     * 
     * @param context the Context to use when resolving the Uri
     * @param uri the Content URI of the data you want to play
     * @throws IllegalArgumentException if the Uri is invalid
     * @throws SecurityException if the Uri cannot be used due to lack of
     * permission.
     */
public void setDataSource(Context context, Uri uri) throws IllegalArgumentException, SecurityException {
    if (uri == null) {
        throw new IllegalArgumentException();
    }
    String scheme = uri.getScheme();
    if (scheme == null || scheme.equals("file")) {
        setDataSource(uri.getPath());
        return;
    }
    AssetFileDescriptor fd = null;
    try {
        ContentResolver resolver = context.getContentResolver();
        try {
            fd = resolver.openAssetFileDescriptor(uri, "r");
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException();
        }
        if (fd == null) {
            throw new IllegalArgumentException();
        }
        FileDescriptor descriptor = fd.getFileDescriptor();
        if (!descriptor.valid()) {
            throw new IllegalArgumentException();
        }
        // a full file.
        if (fd.getDeclaredLength() < 0) {
            setDataSource(descriptor);
        } else {
            setDataSource(descriptor, fd.getStartOffset(), fd.getDeclaredLength());
        }
        return;
    } catch (SecurityException ex) {
    } finally {
        try {
            if (fd != null) {
                fd.close();
            }
        } catch (IOException ioEx) {
        }
    }
    setDataSource(uri.toString());
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) AssetFileDescriptor(android.content.res.AssetFileDescriptor) FileDescriptor(java.io.FileDescriptor) ContentResolver(android.content.ContentResolver)

Example 54 with AssetFileDescriptor

use of android.content.res.AssetFileDescriptor in project android_frameworks_base by AOSPA.

the class CopyJob method copyFileHelper.

/**
     * Handles copying a single file.
     *
     * @param src Info of the file to copy from.
     * @param dest Info of the *file* to copy to. Must be created beforehand.
     * @param destParent Info of the parent of the destination.
     * @param mimeType Mime type for the target. Can be different than source for virtual files.
     * @throws ResourceException
     */
private void copyFileHelper(DocumentInfo src, DocumentInfo dest, DocumentInfo destParent, String mimeType) throws ResourceException {
    CancellationSignal canceller = new CancellationSignal();
    AssetFileDescriptor srcFileAsAsset = null;
    ParcelFileDescriptor srcFile = null;
    ParcelFileDescriptor dstFile = null;
    InputStream in = null;
    ParcelFileDescriptor.AutoCloseOutputStream out = null;
    boolean success = false;
    try {
        // as such format.
        if (src.isVirtualDocument()) {
            try {
                srcFileAsAsset = getClient(src).openTypedAssetFileDescriptor(src.derivedUri, mimeType, null, canceller);
            } catch (FileNotFoundException | RemoteException | RuntimeException e) {
                throw new ResourceException("Failed to open a file as asset for %s due to an " + "exception.", src.derivedUri, e);
            }
            srcFile = srcFileAsAsset.getParcelFileDescriptor();
            try {
                in = new AssetFileDescriptor.AutoCloseInputStream(srcFileAsAsset);
            } catch (IOException e) {
                throw new ResourceException("Failed to open a file input stream for %s due " + "an exception.", src.derivedUri, e);
            }
        } else {
            try {
                srcFile = getClient(src).openFile(src.derivedUri, "r", canceller);
            } catch (FileNotFoundException | RemoteException | RuntimeException e) {
                throw new ResourceException("Failed to open a file for %s due to an exception.", src.derivedUri, e);
            }
            in = new ParcelFileDescriptor.AutoCloseInputStream(srcFile);
        }
        try {
            dstFile = getClient(dest).openFile(dest.derivedUri, "w", canceller);
        } catch (FileNotFoundException | RemoteException | RuntimeException e) {
            throw new ResourceException("Failed to open the destination file %s for writing " + "due to an exception.", dest.derivedUri, e);
        }
        out = new ParcelFileDescriptor.AutoCloseOutputStream(dstFile);
        byte[] buffer = new byte[32 * 1024];
        int len;
        try {
            while ((len = in.read(buffer)) != -1) {
                if (isCanceled()) {
                    if (DEBUG)
                        Log.d(TAG, "Canceled copy mid-copy of: " + src.derivedUri);
                    return;
                }
                out.write(buffer, 0, len);
                makeCopyProgress(len);
            }
            // Need to invoke IoUtils.close explicitly to avoid from ignoring errors at flush.
            IoUtils.close(dstFile.getFileDescriptor());
            srcFile.checkError();
        } catch (IOException e) {
            throw new ResourceException("Failed to copy bytes from %s to %s due to an IO exception.", src.derivedUri, dest.derivedUri, e);
        }
        if (src.isVirtualDocument()) {
            convertedFiles.add(src);
        }
        success = true;
    } finally {
        if (!success) {
            if (dstFile != null) {
                try {
                    dstFile.closeWithError("Error copying bytes.");
                } catch (IOException closeError) {
                    Log.w(TAG, "Error closing destination.", closeError);
                }
            }
            if (DEBUG)
                Log.d(TAG, "Cleaning up failed operation leftovers.");
            canceller.cancel();
            try {
                deleteDocument(dest, destParent);
            } catch (ResourceException e) {
                Log.w(TAG, "Failed to cleanup after copy error: " + src.derivedUri, e);
            }
        }
        // This also ensures the file descriptors are closed.
        IoUtils.closeQuietly(in);
        IoUtils.closeQuietly(out);
    }
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) ParcelFileDescriptor(android.os.ParcelFileDescriptor) RemoteException(android.os.RemoteException) CancellationSignal(android.os.CancellationSignal)

Example 55 with AssetFileDescriptor

use of android.content.res.AssetFileDescriptor in project android_frameworks_base by AOSPA.

the class Ringtone method playFallbackRingtone.

private boolean playFallbackRingtone() {
    if (mAudioManager.getStreamVolume(AudioAttributes.toLegacyStreamType(mAudioAttributes)) != 0) {
        int ringtoneType = RingtoneManager.getDefaultType(mUri);
        if (ringtoneType == -1 || RingtoneManager.getActualDefaultRingtoneUri(mContext, ringtoneType) != null) {
            // Default ringtone, try fallback ringtone.
            try {
                AssetFileDescriptor afd = mContext.getResources().openRawResourceFd(com.android.internal.R.raw.fallbackring);
                if (afd != null) {
                    mLocalPlayer = new MediaPlayer();
                    if (afd.getDeclaredLength() < 0) {
                        mLocalPlayer.setDataSource(afd.getFileDescriptor());
                    } else {
                        mLocalPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
                    }
                    mLocalPlayer.setAudioAttributes(mAudioAttributes);
                    synchronized (mPlaybackSettingsLock) {
                        applyPlaybackProperties_sync();
                    }
                    mLocalPlayer.prepare();
                    startLocalPlayer();
                    afd.close();
                    return true;
                } else {
                    Log.e(TAG, "Could not load fallback ringtone");
                }
            } catch (IOException ioe) {
                destroyLocalPlayer();
                Log.e(TAG, "Failed to open fallback ringtone");
            } catch (NotFoundException nfe) {
                Log.e(TAG, "Fallback ringtone does not exist");
            }
        } else {
            Log.w(TAG, "not playing fallback for " + mUri);
        }
    }
    return false;
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) NotFoundException(android.content.res.Resources.NotFoundException) IOException(java.io.IOException)

Aggregations

AssetFileDescriptor (android.content.res.AssetFileDescriptor)262 IOException (java.io.IOException)147 ParcelFileDescriptor (android.os.ParcelFileDescriptor)57 FileNotFoundException (java.io.FileNotFoundException)56 MediaPlayer (android.media.MediaPlayer)44 ContentResolver (android.content.ContentResolver)36 Test (org.junit.Test)31 Uri (android.net.Uri)30 FileInputStream (java.io.FileInputStream)30 InputStream (java.io.InputStream)23 RemoteException (android.os.RemoteException)22 File (java.io.File)21 Bundle (android.os.Bundle)16 FileDescriptor (java.io.FileDescriptor)16 Nullable (android.annotation.Nullable)15 Bitmap (android.graphics.Bitmap)15 Parcel (android.os.Parcel)14 Resources (android.content.res.Resources)13 BitmapFactory (android.graphics.BitmapFactory)13 DeadObjectException (android.os.DeadObjectException)12