Example usage for android.content.res AssetFileDescriptor getFileDescriptor

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

Introduction

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

Prototype

public FileDescriptor getFileDescriptor() 

Source Link

Document

Returns the FileDescriptor that can be used to read the data in the file.

Usage

From source file:co.tinode.tindroid.ContactsFragment.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 v  a 2  s.co m
 *
 * @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 = Uri.parse(photoData);

        // 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 unused) {
                // 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.hermes.android.NotificationsController.java

public void playOutChatSound() {
    if (!inChatSoundEnabled) {
        return;//from  ww w  . jav  a2s .c o  m
    }
    try {
        if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
            return;
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
    notificationsQueue.postRunnable(new Runnable() {
        @Override
        public void run() {
            try {
                if (mediaPlayerOut == null) {
                    AssetFileDescriptor assetFileDescriptor = ApplicationLoader.applicationContext
                            .getResources().openRawResourceFd(R.raw.sound_out);
                    if (assetFileDescriptor != null) {
                        mediaPlayerOut = new MediaPlayer();
                        mediaPlayerOut.setAudioStreamType(AudioManager.STREAM_SYSTEM);
                        mediaPlayerOut.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                        mediaPlayerOut.setLooping(false);
                        assetFileDescriptor.close();
                        mediaPlayerOut.prepare();
                    }
                }
                mediaPlayerOut.start();
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    });
}

From source file:org.hermes.android.NotificationsController.java

private void playInChatSound() {
    if (!inChatSoundEnabled) {
        return;//  www.  j a va  2  s  . co m
    }
    try {
        if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
            return;
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }

    try {
        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
        int notify_override = preferences.getInt("notify2_" + openned_dialog_id, 0);
        if (notify_override == 3) {
            int mute_until = preferences.getInt("notifyuntil_" + openned_dialog_id, 0);
            if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {
                notify_override = 2;
            }
        }
        if (notify_override == 2) {
            return;
        }
        notificationsQueue.postRunnable(new Runnable() {
            @Override
            public void run() {
                if (lastSoundPlay > System.currentTimeMillis() - 500) {
                    return;
                }
                try {
                    if (mediaPlayerIn == null) {
                        AssetFileDescriptor assetFileDescriptor = ApplicationLoader.applicationContext
                                .getResources().openRawResourceFd(R.raw.sound_in);
                        if (assetFileDescriptor != null) {
                            mediaPlayerIn = new MediaPlayer();
                            mediaPlayerIn.setAudioStreamType(AudioManager.STREAM_SYSTEM);
                            mediaPlayerIn.setDataSource(assetFileDescriptor.getFileDescriptor(),
                                    assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
                            mediaPlayerIn.setLooping(false);
                            assetFileDescriptor.close();
                            mediaPlayerIn.prepare();
                        }
                    }
                    mediaPlayerIn.start();
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            }
        });
        /*String choosenSoundPath = null;
        String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath();
                
        choosenSoundPath = preferences.getString("sound_path_" + openned_dialog_id, null);
        boolean isChat = (int)(openned_dialog_id) < 0;
        if (isChat) {
        if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
            choosenSoundPath = null;
        } else if (choosenSoundPath == null) {
            choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath);
        }
        } else {
        if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
            choosenSoundPath = null;
        } else if (choosenSoundPath == null) {
            choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath);
        }
        }
                
        if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
        if (lastMediaPlayerUri == null || !choosenSoundPath.equals(lastMediaPlayerUri)) {
            lastMediaPlayerUri = choosenSoundPath;
            mediaPlayer.reset();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            if (choosenSoundPath.equals(defaultPath)) {
                mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Settings.System.DEFAULT_NOTIFICATION_URI);
            } else {
                mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Uri.parse(choosenSoundPath));
            }
            mediaPlayer.prepare();
        }
        mediaPlayer.start();
        }*/
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:com.mitre.holdshort.MainActivity.java

private void playAlert() {

    // Check if the user wants aural alerts
    if (auralAlerts) {

        // Check and make sure counter is less than the size of the list
        // If not, clear sounds and reset counter
        if (soundNum < sounds.size()) {
            try {
                // Go through each of the sounds and see if the current
                // sound matches
                // If it does then set the dataSource for the player and
                // play
                // When the sound is done playing the finish callback
                // increments soundNum
                // and sends it back to this method.

                if (sounds.get(soundNum).equalsIgnoreCase("HOLD_SHORT")) {

                    AssetFileDescriptor afd = getAssets().openFd("holdShortOfRunway.mp3");
                    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                    mp.prepare();/*w w w.ja  v a2  s.c  o  m*/
                    mp.start();
                }

                if (sounds.get(soundNum).equalsIgnoreCase("CROSSING")) {
                    AssetFileDescriptor afd = getAssets().openFd("crossingRunway.mp3");
                    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                    mp.prepare();
                    mp.start();
                }
                if (sounds.get(soundNum).equalsIgnoreCase("NO_CLEARANCE")) {
                    AssetFileDescriptor afd = getAssets().openFd("holdShortNoClearanceForRunway.mp3");
                    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                    mp.prepare();
                    mp.start();
                }

                if (sounds.get(soundNum).equalsIgnoreCase("WRONG_RUNWAY")) {

                    AssetFileDescriptor afd = getAssets().openFd("noTakeoffClearance.mp3");
                    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                    mp.prepare();
                    mp.start();
                }

                if (settings.getBoolean("announceRWY", true)) {

                    if (sounds.get(soundNum).equalsIgnoreCase("1")) {
                        AssetFileDescriptor afd = getAssets().openFd("1.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("2")) {
                        AssetFileDescriptor afd = getAssets().openFd("2.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("3")) {
                        AssetFileDescriptor afd = getAssets().openFd("3.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("4")) {
                        AssetFileDescriptor afd = getAssets().openFd("4.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("5")) {
                        AssetFileDescriptor afd = getAssets().openFd("5.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("6")) {
                        AssetFileDescriptor afd = getAssets().openFd("6.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("7")) {
                        AssetFileDescriptor afd = getAssets().openFd("7.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("8")) {
                        AssetFileDescriptor afd = getAssets().openFd("8.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("9")) {
                        AssetFileDescriptor afd = getAssets().openFd("9.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("0")) {
                        AssetFileDescriptor afd = getAssets().openFd("0.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("L")) {
                        AssetFileDescriptor afd = getAssets().openFd("left.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("C")) {
                        AssetFileDescriptor afd = getAssets().openFd("center.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                    if (sounds.get(soundNum).equalsIgnoreCase("R")) {
                        AssetFileDescriptor afd = getAssets().openFd("right.mp3");
                        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                        mp.prepare();
                        mp.start();
                    }
                }
            } catch (IOException e) {

            }

        } else {
            sounds.clear();
            soundNum = 0;
        }
    }
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Plays the specified sound from the application asset folder.
 * /*from   w  w w.  j  a  v  a  2  s .  c  om*/
 * @param context
 * @param assetSoundPath   Path to the sound in the assets folder.
 */
public static void media_soundPlayFromAssetFolder(Context context, String assetSoundPath) {
    try {
        AssetFileDescriptor afd = context.getAssets().openFd(assetSoundPath);

        MediaPlayer player = new MediaPlayer();
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        player.prepare();
        player.start();

    } catch (Exception e) {
        if (LOG_ENABLE) {
            Log.e(TAG, "Error playing sound: '" + assetSoundPath + "' (" + e.getMessage() + ")", e);
        }
    }
}

From source file:learn2crack.activities.WnContactsListFragment.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 ava  2  s  .  co  m*/
 *
 * @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) {

    } 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:android.com.example.contactslist.ui.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.//ww w.j  av a  2s  . c  o  m
 *
 * @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:fr.jbteam.jabboid.core.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 . ja  v a2  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:br.com.mybaby.contatos.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  v a2  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:com.forktech.cmerge.ui.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.
 *
 * @param photoData//from  www.  j  av a  2  s  .c  o  m
 *            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;
}