Example usage for android.content.res AssetFileDescriptor close

List of usage examples for android.content.res AssetFileDescriptor close

Introduction

In this page you can find the example usage for android.content.res AssetFileDescriptor close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Convenience for calling getParcelFileDescriptor().close().

Usage

From source file:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactsListFragment.java

/**
 * Decodes and scales a contact's image from a file pointed to by a Uri in the contact's data,
 * and returns the result as a Bitmap. The column that contains the Uri varies according to the
 * platform version.//w  w  w.java2  s  . c  om
 *
 * @param photoData For platforms prior to Android 3.0, provide the Contact._ID column value.
 *                  For Android 3.0 and later, provide the Contact.PHOTO_THUMBNAIL_URI value.
 * @param imageSize The desired target width and height of the output image in pixels.
 * @return A Bitmap containing the contact's image, resized to fit the provided image size. If
 * no thumbnail exists, returns null.
 */
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {

    // Ensures the Fragment is still added to an activity. As this method is called in a
    // background thread, there's the possibility the Fragment is no longer attached and
    // added to an activity. If so, no need to spend resources loading the contact photo.
    if (!isAdded() || getActivity() == null) {
        return null;
    }

    // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the
    // ContentResolver can return an AssetFileDescriptor for the file.
    AssetFileDescriptor afd = null;

    // This "try" block catches an Exception if the file descriptor returned from the Contacts
    // Provider doesn't point to an existing file.
    try {
        Uri thumbUri;
        // If Android 3.0 or later, converts the Uri passed as a string to a Uri object.
        if (Utils.hasHoneycomb()) {
            thumbUri = Uri.parse(photoData);
        } else {
            // For versions prior to Android 3.0, appends the string argument to the content
            // Uri for the Contacts table.
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);

            // Appends the content Uri for the Contacts.Photo table to the previously
            // constructed contact Uri to yield a content URI for the thumbnail image
            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }
        // Retrieves a file descriptor from the Contacts Provider. To learn more about this
        // feature, read the reference documentation for
        // ContentResolver#openAssetFileDescriptor.
        afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");

        // Gets a FileDescriptor from the AssetFileDescriptor. A BitmapFactory object can
        // decode the contents of a file pointed to by a FileDescriptor into a Bitmap.
        FileDescriptor fileDescriptor = afd.getFileDescriptor();

        if (fileDescriptor != null) {
            // Decodes a Bitmap from the image pointed to by the FileDescriptor, and scales it
            // to the specified width and height
            return ImageLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {
        // If the file pointed to by the thumbnail URI doesn't exist, or the file can't be
        // opened in "read" mode, ContentResolver.openAssetFileDescriptor throws a
        // FileNotFoundException.
        if (BuildConfig.DEBUG) {
            //                Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData
            //                        + ": " + e.toString());
        }
    } finally {
        // If an AssetFileDescriptor was returned, try to close it
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
                // Closing a file descriptor might cause an IOException if the file is
                // already closed. Nothing extra is needed to handle this.
            }
        }
    }

    // If the decoding failed, returns null
    return null;
}

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

private void playBeep(boolean error) {

    if (!isAdded()) {
        return;//w  ww .  j  av  a  2s.c o m
    }

    try {
        MediaPlayer beepPlayer = new MediaPlayer();

        String file = "beep.mp3";

        if (error) {
            file = "error.mp3";
        }

        AssetFileDescriptor descriptor = context.getAssets().openFd(file);
        beepPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(),
                descriptor.getLength());
        descriptor.close();

        beepPlayer.prepare();

        beepPlayer.start();
    } catch (Exception io) {
        // We'll manage without the beep :)
    }
}

From source file:com.dsdar.thosearoundme.util.ContactsListFragment.java

/**
 * Decodes and scales a contact's image from a file pointed to by a Uri in
 * the contact's data, and returns the result as a Bitmap. The column that
 * contains the Uri varies according to the platform version.
 * /*from   w w  w .j a  va 2 s . com*/
 * @param photoData
 *            For platforms prior to Android 3.0, provide the Contact._ID
 *            column value. For Android 3.0 and later, provide the
 *            Contact.PHOTO_THUMBNAIL_URI value.
 * @param imageSize
 *            The desired target width and height of the output image in
 *            pixels.
 * @return A Bitmap containing the contact's image, resized to fit the
 *         provided image size. If no thumbnail exists, returns null.
 */
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {

    // Ensures the Fragment is still added to an activity. As this method is
    // called in a
    // background thread, there's the possibility the Fragment is no longer
    // attached and
    // added to an activity. If so, no need to spend resources loading the
    // contact photo.
    if (!isAdded() || getActivity() == null) {
        return null;
    }

    // Instantiates an AssetFileDescriptor. Given a content Uri pointing to
    // an image file, the
    // ContentResolver can return an AssetFileDescriptor for the file.
    AssetFileDescriptor afd = null;

    // This "try" block catches an Exception if the file descriptor returned
    // from the Contacts
    // Provider doesn't point to an existing file.
    try {
        Uri thumbUri;
        // If Android 3.0 or later, converts the Uri passed as a string to a
        // Uri object.
        if (Util.hasHoneycomb()) {
            thumbUri = Uri.parse(photoData);
        } else {
            // For versions prior to Android 3.0, appends the string
            // argument to the content
            // Uri for the Contacts table.
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);

            // Appends the content Uri for the Contacts.Photo table to the
            // previously
            // constructed contact Uri to yield a content URI for the
            // thumbnail image
            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }
        // Retrieves a file descriptor from the Contacts Provider. To learn
        // more about this
        // feature, read the reference documentation for
        // ContentResolver#openAssetFileDescriptor.
        afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");

        // Gets a FileDescriptor from the AssetFileDescriptor. A
        // BitmapFactory object can
        // decode the contents of a file pointed to by a FileDescriptor into
        // a Bitmap.
        FileDescriptor fileDescriptor = afd.getFileDescriptor();

        if (fileDescriptor != null) {
            // Decodes a Bitmap from the image pointed to by the
            // FileDescriptor, and scales it
            // to the specified width and height
            return ImageLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {
        // If the file pointed to by the thumbnail URI doesn't exist, or the
        // file can't be
        // opened in "read" mode, ContentResolver.openAssetFileDescriptor
        // throws a
        // FileNotFoundException.
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData + ": " + e.toString());
        }
    } finally {
        // If an AssetFileDescriptor was returned, try to close it
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
                // Closing a file descriptor might cause an IOException if
                // the file is
                // already closed. Nothing extra is needed to handle this.
            }
        }
    }

    // If the decoding failed, returns null
    return null;
}

From source file:org.opendatakit.tables.tasks.InitializeTask.java

private void extractFromRawZip(int resourceId, boolean overwrite, ArrayList<String> result) {
    String message = null;/*from w  ww .j ava  2 s  .  c  om*/
    AssetFileDescriptor fd = null;
    try {
        fd = mContext.getResources().openRawResourceFd(resourceId);
        final long size = fd.getLength() / 2L; // apparently over-counts by 2x?
        InputStream rawInputStream = null;
        try {
            rawInputStream = fd.createInputStream();
            ZipInputStream zipInputStream = null;
            ZipEntry entry = null;
            try {

                // count the number of files in the zip
                zipInputStream = new ZipInputStream(rawInputStream);
                int totalFiles = 0;
                while ((entry = zipInputStream.getNextEntry()) != null) {
                    message = null;
                    if (isCancelled()) {
                        message = "cancelled";
                        result.add(entry.getName() + " " + message);
                        break;
                    }
                    ++totalFiles;
                }
                zipInputStream.close();

                // and re-open the stream, reading it this time...
                fd = mContext.getResources().openRawResourceFd(resourceId);
                rawInputStream = fd.createInputStream();
                zipInputStream = new ZipInputStream(rawInputStream);

                long bytesProcessed = 0L;
                long lastBytesProcessedThousands = 0L;
                int nFiles = 0;
                while ((entry = zipInputStream.getNextEntry()) != null) {
                    message = null;
                    if (isCancelled()) {
                        message = "cancelled";
                        result.add(entry.getName() + " " + message);
                        break;
                    }
                    ++nFiles;
                    File tempFile = new File(ODKFileUtils.getAppFolder(mAppName), entry.getName());
                    String formattedString = mContext.getString(R.string.expansion_unzipping_without_detail,
                            entry.getName(), nFiles, totalFiles);
                    String detail;
                    if (entry.isDirectory()) {
                        detail = mContext.getString(R.string.expansion_create_dir_detail);
                        publishProgress(formattedString, detail);
                        tempFile.mkdirs();
                    } else {
                        int bufferSize = 8192;
                        OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false),
                                bufferSize);
                        byte buffer[] = new byte[bufferSize];
                        int bread;
                        while ((bread = zipInputStream.read(buffer)) != -1) {
                            bytesProcessed += bread;
                            long curThousands = (bytesProcessed / 1000L);
                            if (curThousands != lastBytesProcessedThousands) {
                                detail = mContext.getString(R.string.expansion_unzipping_detail, bytesProcessed,
                                        size);
                                publishProgress(formattedString, detail);
                                lastBytesProcessedThousands = curThousands;
                            }
                            out.write(buffer, 0, bread);
                        }
                        out.flush();
                        out.close();

                        detail = mContext.getString(R.string.expansion_unzipping_detail, bytesProcessed, size);
                        publishProgress(formattedString, detail);
                    }
                    WebLogger.getLogger(mAppName).i(TAG, "Extracted ZipEntry: " + entry.getName());

                    message = mContext.getString(R.string.success);
                    result.add(entry.getName() + " " + message);
                }

                ODKFileUtils.assertConfiguredTablesApp(mAppName, Tables.getInstance().getVersionCodeString());

                String completionString = mContext.getString(R.string.expansion_unzipping_complete, totalFiles);
                publishProgress(completionString, null);
            } catch (IOException e) {
                WebLogger.getLogger(mAppName).printStackTrace(e);
                mPendingSuccess = false;
                if (e.getCause() != null) {
                    message = e.getCause().getMessage();
                } else {
                    message = e.getMessage();
                }
                if (entry != null) {
                    result.add(entry.getName() + " " + message);
                } else {
                    result.add("Error accessing zipfile resource " + message);
                }
            } finally {
                if (zipInputStream != null) {
                    try {
                        zipInputStream.close();
                        rawInputStream = null;
                        fd = null;
                    } catch (IOException e) {
                        WebLogger.getLogger(mAppName).printStackTrace(e);
                        WebLogger.getLogger(mAppName).e(TAG, "Closing of ZipFile failed: " + e.toString());
                    }
                }
                if (rawInputStream != null) {
                    try {
                        rawInputStream.close();
                        fd = null;
                    } catch (IOException e) {
                        WebLogger.getLogger(mAppName).printStackTrace(e);
                        WebLogger.getLogger(mAppName).e(TAG, "Closing of ZipFile failed: " + e.toString());
                    }
                }
                if (fd != null) {
                    try {
                        fd.close();
                    } catch (IOException e) {
                        WebLogger.getLogger(mAppName).printStackTrace(e);
                        WebLogger.getLogger(mAppName).e(TAG, "Closing of ZipFile failed: " + e.toString());
                    }
                }
            }
        } catch (Exception e) {
            WebLogger.getLogger(mAppName).printStackTrace(e);
            mPendingSuccess = false;
            if (e.getCause() != null) {
                message = e.getCause().getMessage();
            } else {
                message = e.getMessage();
            }
            result.add("Error accessing zipfile resource " + message);
        } finally {
            if (rawInputStream != null) {
                try {
                    rawInputStream.close();
                } catch (IOException e) {
                    WebLogger.getLogger(mAppName).printStackTrace(e);
                }
            }
        }
    } finally {
        if (fd != null) {
            try {
                fd.close();
            } catch (IOException e) {
                WebLogger.getLogger(mAppName).printStackTrace(e);
            }
        } else {
            result.add("Error accessing zipfile resource.");
        }
    }
}

From source file:org.opendatakit.survey.android.tasks.InitializationTask.java

private final void extractFromRawZip(int resourceId, boolean overwrite, ArrayList<String> result) {
    String message = null;//  w ww.ja v a  2  s .  c om
    AssetFileDescriptor fd = null;
    try {
        fd = appContext.getResources().openRawResourceFd(resourceId);
        final long size = fd.getLength(); // apparently over-counts by 2x?
        InputStream rawInputStream = null;
        try {
            rawInputStream = fd.createInputStream();
            ZipInputStream zipInputStream = null;
            ZipEntry entry = null;
            try {

                // count the number of files in the zip
                zipInputStream = new ZipInputStream(rawInputStream);
                int totalFiles = 0;
                while ((entry = zipInputStream.getNextEntry()) != null) {
                    message = null;
                    if (isCancelled()) {
                        message = "cancelled";
                        result.add(entry.getName() + " " + message);
                        break;
                    }
                    ++totalFiles;
                }
                zipInputStream.close();

                // and re-open the stream, reading it this time...
                fd = appContext.getResources().openRawResourceFd(resourceId);
                rawInputStream = fd.createInputStream();
                zipInputStream = new ZipInputStream(rawInputStream);

                long bytesProcessed = 0L;
                long lastBytesProcessedThousands = 0L;
                int nFiles = 0;
                while ((entry = zipInputStream.getNextEntry()) != null) {
                    message = null;
                    if (isCancelled()) {
                        message = "cancelled";
                        result.add(entry.getName() + " " + message);
                        break;
                    }
                    ++nFiles;
                    File tempFile = new File(ODKFileUtils.getAppFolder(appName), entry.getName());
                    String formattedString = appContext.getString(R.string.expansion_unzipping_without_detail,
                            entry.getName(), nFiles, totalFiles);
                    String detail;
                    if (entry.isDirectory()) {
                        detail = appContext.getString(R.string.expansion_create_dir_detail);
                        publishProgress(formattedString, detail);
                        tempFile.mkdirs();
                    } else if (overwrite || !tempFile.exists()) {
                        int bufferSize = 8192;
                        OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false),
                                bufferSize);
                        byte buffer[] = new byte[bufferSize];
                        int bread;
                        while ((bread = zipInputStream.read(buffer)) != -1) {
                            bytesProcessed += bread;
                            long curThousands = (bytesProcessed / 1000L);
                            if (curThousands != lastBytesProcessedThousands) {
                                detail = appContext.getString(R.string.expansion_unzipping_detail,
                                        bytesProcessed, size);
                                publishProgress(formattedString, detail);
                                lastBytesProcessedThousands = curThousands;
                            }
                            out.write(buffer, 0, bread);
                        }
                        out.flush();
                        out.close();

                        detail = appContext.getString(R.string.expansion_unzipping_detail, bytesProcessed,
                                size);
                        publishProgress(formattedString, detail);
                    }
                    WebLogger.getLogger(appName).i(t, "Extracted ZipEntry: " + entry.getName());
                }

                String completionString = appContext.getString(R.string.expansion_unzipping_complete,
                        totalFiles);
                publishProgress(completionString, null);
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                mPendingSuccess = false;
                if (e.getCause() != null) {
                    message = e.getCause().getMessage();
                } else {
                    message = e.getMessage();
                }
                if (entry != null) {
                    result.add(entry.getName() + " " + message);
                } else {
                    result.add("Error accessing zipfile resource " + message);
                }
            } finally {
                if (zipInputStream != null) {
                    try {
                        zipInputStream.close();
                    } catch (IOException e) {
                        WebLogger.getLogger(appName).printStackTrace(e);
                        WebLogger.getLogger(appName).e(t, "Closing of ZipFile failed: " + e.toString());
                    }
                }
            }
        } catch (Exception e) {
            WebLogger.getLogger(appName).printStackTrace(e);
            mPendingSuccess = false;
            if (e.getCause() != null) {
                message = e.getCause().getMessage();
            } else {
                message = e.getMessage();
            }
            result.add("Error accessing zipfile resource " + message);
        } finally {
            if (rawInputStream != null) {
                try {
                    rawInputStream.close();
                } catch (IOException e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                }
            }
        }
    } finally {
        if (fd != null) {
            try {
                fd.close();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
            }
        } else {
            result.add("Error accessing zipfile resource.");
        }
    }
}