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:com.kjsaw.alcosys.ibacapp.IBAC.java

private void initBeepSound() {
    if (mediaPlayerBeep == null) {
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mediaPlayerBeep = new MediaPlayer();
        mediaPlayerBeep.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayerBeep.setOnCompletionListener(beepListener);

        AssetFileDescriptor fileBeep = getResources().openRawResourceFd(R.raw.beep);
        try {// ww  w.j a  va2s  .c om
            mediaPlayerBeep.setDataSource(fileBeep.getFileDescriptor(), fileBeep.getStartOffset(),
                    fileBeep.getLength());
            fileBeep.close();
            mediaPlayerBeep.setVolume(BEEP_VOLUME, BEEP_VOLUME);
            mediaPlayerBeep.prepare();
        } catch (IOException e) {
            mediaPlayerBeep = null;
        }
    }
}

From source file:fr.bde_eseo.eseomega.GantierActivity.java

@Override
public void onResume() {
    super.onResume();

    /*/* w  w w.  j  a v a 2 s . com*/
    senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_GAME);*/
    initListeners();

    // wait for one second until gyroscope and magnetometer/accelerometer
    // data is initialised then scedule the complementary filter task
    fuseTimer.scheduleAtFixedRate(new calculateFusedOrientationTask(), 1000, TIME_CONSTANT);

    // if not playing
    if (!mediaPlayer.isPlaying()) {
        AssetFileDescriptor descriptor = null;
        try {
            descriptor = getAssets().openFd("wabe.mp3");
            mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(),
                    descriptor.getLength());
            descriptor.close();
            mediaPlayer.prepare();
            mediaPlayer.setLooping(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Start music !
    mediaPlayer.start();
}

From source file:com.kjsaw.alcosys.ibacapp.IBAC.java

private void initCaptureSound() {
    if (mediaPlayerCapture == null) {
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mediaPlayerCapture = new MediaPlayer();
        mediaPlayerCapture.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayerCapture.setOnCompletionListener(captureListener);

        AssetFileDescriptor fileBeep = getResources().openRawResourceFd(R.raw.camera_flash);
        try {//  w  w w .  j a  v a2  s  .c o  m
            mediaPlayerCapture.setDataSource(fileBeep.getFileDescriptor(), fileBeep.getStartOffset(),
                    fileBeep.getLength());
            fileBeep.close();
            mediaPlayerCapture.setVolume(CAPTURE_VOLUME, CAPTURE_VOLUME);
            mediaPlayerCapture.prepare();
        } catch (IOException e) {
            mediaPlayerCapture = null;
        }
    }
}

From source file:com.fa.mastodon.activity.ComposeActivity.java

private boolean onCommitContentInternal(InputContentInfoCompat inputContentInfo, int flags) {
    if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
        try {//from w  ww.j ava 2  s  . co m
            inputContentInfo.requestPermission();
        } catch (Exception e) {
            Log.e(TAG, "InputContentInfoCompat#requestPermission() failed." + e.getMessage());
            return false;
        }
    }

    // Determine the file size before putting handing it off to be put in the queue.
    Uri uri = inputContentInfo.getContentUri();
    long mediaSize;
    AssetFileDescriptor descriptor = null;
    try {
        descriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
    } catch (FileNotFoundException e) {
        // Eat this exception, having the descriptor be null is sufficient.
    }
    if (descriptor != null) {
        mediaSize = descriptor.getLength();
        try {
            descriptor.close();
        } catch (IOException e) {
            // Just eat this exception.
        }
    } else {
        mediaSize = MEDIA_SIZE_UNKNOWN;
    }
    pickMedia(uri, mediaSize);

    currentInputContentInfo = inputContentInfo;
    currentFlags = flags;

    return true;
}

From source file:com.android.contacts.common.model.ContactLoader.java

/**
 * Looks for the photo data item in entities. If found, a thumbnail will be stored. A larger
 * photo will also be stored if available.
 *//*from w w w . ja  v  a2s  .c o m*/
private void loadPhotoBinaryData(Contact contactData) {
    loadThumbnailBinaryData(contactData);

    // Try to load the large photo from a file using the photo URI.
    String photoUri = contactData.getPhotoUri();
    if (photoUri != null) {
        try {
            final InputStream inputStream;
            final AssetFileDescriptor fd;
            final Uri uri = Uri.parse(photoUri);
            final String scheme = uri.getScheme();
            if ("http".equals(scheme) || "https".equals(scheme)) {
                // Support HTTP urls that might come from extended directories
                inputStream = new URL(photoUri).openStream();
                fd = null;
            } else {
                fd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r");
                inputStream = fd.createInputStream();
            }
            byte[] buffer = new byte[16 * 1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                int size;
                while ((size = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, size);
                }
                contactData.setPhotoBinaryData(baos.toByteArray());
            } finally {
                inputStream.close();
                if (fd != null) {
                    fd.close();
                }
            }
            return;
        } catch (IOException ioe) {
            // Just fall back to the case below.
        }
    }

    // If we couldn't load from a file, fall back to the data blob.
    contactData.setPhotoBinaryData(contactData.getThumbnailPhotoBinaryData());
}

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

public void playOutChatSound() {
    if (!inChatSoundEnabled) {
        return;//from ww  w .j  av  a  2s .  co 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:com.keylesspalace.tusky.ComposeActivity.java

private boolean onCommitContentInternal(InputContentInfoCompat inputContentInfo, int flags) {
    if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
        try {/*from  w  ww. j  a v a  2  s.  co  m*/
            inputContentInfo.requestPermission();
        } catch (Exception e) {
            Log.e(TAG, "InputContentInfoCompat#requestPermission() failed." + e.getMessage());
            return false;
        }
    }

    // Determine the file size before putting handing it off to be put in the queue.
    Uri uri = inputContentInfo.getContentUri();
    long mediaSize;
    AssetFileDescriptor descriptor = null;
    try {
        descriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
    } catch (FileNotFoundException e) {
        Log.d(TAG, Log.getStackTraceString(e));
        // Eat this exception, having the descriptor be null is sufficient.
    }
    if (descriptor != null) {
        mediaSize = descriptor.getLength();
        try {
            descriptor.close();
        } catch (IOException e) {
            // Just eat this exception.
        }
    } else {
        mediaSize = MediaUtils.MEDIA_SIZE_UNKNOWN;
    }
    pickMedia(uri, mediaSize);

    currentInputContentInfo = inputContentInfo;
    currentFlags = flags;

    return true;
}

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

private void playInChatSound() {
    if (!inChatSoundEnabled) {
        return;//from w w w . jav  a 2s. 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.example.fragmentexercise.ContactsAdapter.java

/**
 * Load a contact photo thumbnail and return it as a Bitmap, resizing the
 * image to the provided image dimensions as needed.
 * //from w w w .  ja v a 2 s.  c o m
 * @param photoData
 *            photo ID Prior to Honeycomb, the contact's _ID value. For
 *            Honeycomb and later, the value of PHOTO_THUMBNAIL_URI.
 * @return A thumbnail Bitmap, sized to the provided width and height.
 *         Returns null if the thumbnail is not found.
 */
private Bitmap loadContactPhotoThumbnail(String photoData) {
    // Creates an asset file descriptor for the thumbnail file.
    AssetFileDescriptor afd = null;
    // try-catch block for file not found
    try {
        // Creates a holder for the URI.
        Uri thumbUri;
        // If Android 3.0 or later
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Sets the URI from the incoming PHOTO_THUMBNAIL_URI
            thumbUri = Uri.parse(photoData);
        } else {
            // Prior to Android 3.0, constructs a photo Uri using _ID
            /*
             * Creates a contact URI from the Contacts content URI incoming
             * photoData (_ID)
             */
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);
            /*
             * Creates a photo URI by appending the content URI of
             * Contacts.Photo.
             */
            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }

        /*
         * Retrieves an AssetFileDescriptor object for the thumbnail URI
         * using ContentResolver.openAssetFileDescriptor
         */
        afd = mContext.getContentResolver().openAssetFileDescriptor(thumbUri, "r");
        /*
         * Gets a file descriptor from the asset file descriptor. This
         * object can be used across processes.
         */
        FileDescriptor fileDescriptor = afd.getFileDescriptor();
        // Decode the photo file and return the result as a Bitmap
        // If the file descriptor is valid
        if (fileDescriptor != null) {
            // Decodes the bitmap
            return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, null);
        }
        // If the file isn't found
    } catch (FileNotFoundException e) {
        /*
         * Handle file not found errors
         */
    }
    // In all cases, close the asset file descriptor
    finally {
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:fr.jbteam.jabboid.core.ContactDetailFragment.java

/**
 * Decodes and returns the contact's thumbnail image.
 * @param contactUri The Uri of the contact containing the image.
 * @param imageSize The desired target width and height of the output image in pixels.
 * @return If a thumbnail image exists for the contact, a Bitmap image, otherwise null.
 *//*from ww w.ja v a  2s.co  m*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private Bitmap loadContactPhoto(Uri contactUri, 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 a ContentResolver for retrieving the Uri of the image
    final ContentResolver contentResolver = getActivity().getContentResolver();

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

    if (Utils.hasICS()) {
        // On platforms running Android 4.0 (API version 14) and later, a high resolution image
        // is available from Photo.DISPLAY_PHOTO.
        try {
            // Constructs the content Uri for the image
            Uri displayImageUri = Uri.withAppendedPath(contactUri, Photo.DISPLAY_PHOTO);

            // Retrieves an AssetFileDescriptor from the Contacts Provider, using the
            // constructed Uri
            afd = contentResolver.openAssetFileDescriptor(displayImageUri, "r");
            // If the file exists
            if (afd != null) {
                // Reads and decodes the file to a Bitmap and scales it to the desired size
                return ImageLoader.decodeSampledBitmapFromDescriptor(afd.getFileDescriptor(), imageSize,
                        imageSize);
            }
        } catch (FileNotFoundException e) {
            // Catches file not found exceptions
            /*if (BuildConfig.DEBUG) {
            // Log debug message, this is not an error message as this exception is thrown
            // when a contact is legitimately missing a contact photo (which will be quite
            // frequently in a long contacts list).
            Log.d(TAG, "Contact photo not found for contact " + contactUri.toString()
                    + ": " + e.toString());
            }*/
        } finally {
            // Once the decode is complete, this closes the file. You must do this each time
            // you access an AssetFileDescriptor; otherwise, every image load you do will open
            // a new descriptor.
            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 platform version is less than Android 4.0 (API Level 14), use the only available
    // image URI, which points to a normal-sized image.
    try {
        // Constructs the image Uri from the contact Uri and the directory twig from the
        // Contacts.Photo table
        Uri imageUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);

        // Retrieves an AssetFileDescriptor from the Contacts Provider, using the constructed
        // Uri
        afd = getActivity().getContentResolver().openAssetFileDescriptor(imageUri, "r");

        // If the file exists
        if (afd != null) {
            // Reads the image from the file, decodes it, and scales it to the available screen
            // area
            return ImageLoader.decodeSampledBitmapFromDescriptor(afd.getFileDescriptor(), imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {
        // Catches file not found exceptions
        /*if (BuildConfig.DEBUG) {
        // Log debug message, this is not an error message as this exception is thrown
        // when a contact is legitimately missing a contact photo (which will be quite
        // frequently in a long contacts list).
        Log.d(TAG, "Contact photo not found for contact " + contactUri.toString()
                + ": " + e.toString());
        }*/
    } finally {
        // Once the decode is complete, this closes the file. You must do this each time you
        // access an AssetFileDescriptor; otherwise, every image load you do will open a new
        // descriptor.
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
                // Closing a file descriptor might cause an IOException if the file is
                // already closed. Ignore this.
            }
        }
    }

    // If none of the case selectors match, returns null.
    return null;
}