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.xlythe.engine.theme.Theme.java

public static long getDurationOfSound(Context context, Theme.Res res) {
    int millis = 0;
    MediaPlayer mp = new MediaPlayer();
    try {// w  w  w .  j  a v  a2  s. c om
        AssetFileDescriptor afd;
        int id = getId(context, res.getType(), res.getName());
        if (id == 0) {
            id = context.getResources().getIdentifier(res.getName(), res.getType(), context.getPackageName());
            afd = context.getResources().openRawResourceFd(id);
        }

        afd = getThemeContext(context).getResources().openRawResourceFd(id);
        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        afd.close();
        mp.prepare();
        millis = mp.getDuration();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        mp.release();
        mp = null;
    }

    return millis;
}

From source file:Main.java

public static Bitmap decodeSampledBitmapFromFile(Resources res, ContentResolver contentResolver, Uri uri,
        float reqWidthInDip, float reqHeightInDip) throws IOException {

    Bitmap bitmap;/*from ww  w.  java 2  s. co m*/
    AssetFileDescriptor fileDescriptor;
    int reqWidthInPixel = (int) dipToPixels(res, reqWidthInDip);
    int reqHeightInPixel = (int) dipToPixels(res, reqHeightInDip);
    fileDescriptor = contentResolver.openAssetFileDescriptor(uri, "r");

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidthInPixel, reqHeightInPixel);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
    fileDescriptor.close();
    return bitmap;
}

From source file:Main.java

public static Bitmap decodeSampledBitmapFromFile(Resources res, ContentResolver contentResolver, File file,
        float reqWidthInDip, float reqHeightInDip) throws IOException {

    Bitmap bitmap;//from w ww  . jav  a  2  s  . c o m
    AssetFileDescriptor fileDescriptor;
    int reqWidthInPixel = (int) dipToPixels(res, reqWidthInDip);
    int reqHeightInPixel = (int) dipToPixels(res, reqHeightInDip);
    fileDescriptor = contentResolver.openAssetFileDescriptor(Uri.fromFile(file), "r");

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidthInPixel, reqHeightInPixel);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
    fileDescriptor.close();
    return bitmap;
}

From source file:it.interfree.leonardoce.bootreceiver.AlarmKlaxon.java

private void setDataSourceFromResource(Resources resources, MediaPlayer player, int res)
        throws java.io.IOException {
    AssetFileDescriptor afd = resources.openRawResourceFd(res);
    if (afd != null) {
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        afd.close();
    }/*  w  w  w .  jav a2  s .c  om*/
}

From source file:com.wsi.audiodemo.ScrollingActivity.java

private void playSound2(String assetName) {
    try {/*from w  w w  .  ja  va  2 s . com*/
        // Syntax  :  android.resource://[package]/[res type]/[res name]
        // Example : Uri.parse("android.resource://com.my.package/raw/sound1");
        //
        // Syntax  : android.resource://[package]/[resource_id]
        // Example : Uri.parse("android.resource://com.my.package/" + R.raw.sound1);

        String RESOURCE_PATH = ContentResolver.SCHEME_ANDROID_RESOURCE + "://";

        String path;
        if (false) {
            path = RESOURCE_PATH + getPackageName() + "/raw/" + assetName;
        } else {
            int resID = getResources().getIdentifier(assetName, "raw", getPackageName());
            path = RESOURCE_PATH + getPackageName() + File.separator + resID;
        }
        Uri soundUri = Uri.parse(path);
        mSoundName.setText(path);

        mMediaPlayer = new MediaPlayer();
        if (true) {
            mMediaPlayer.setDataSource(getApplicationContext(), soundUri);
            mMediaPlayer.prepare();
        } else if (false) {
            // How to load external audio files.
            // "/sdcard/sample.mp3";
            //  "http://www.bogotobogo.com/Audio/sample.mp3";
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.prepare();
        } else {
            ContentResolver resolver = getContentResolver();
            AssetFileDescriptor afd = resolver.openAssetFileDescriptor(soundUri, "r");
            mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            afd.close();
        }

        mMediaPlayer.start();
    } catch (Exception ex) {
        Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:com.wsi.audiodemo.ScrollingActivity.java

private void playSound3(String assetName) {
    try {//from  w ww.j  a v a  2  s.  com
        AssetFileDescriptor afd = getAssets().openFd("sounds/" + assetName + ".mp3");
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        afd.close();
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    } catch (Exception ex) {
        Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:com.adkdevelopment.simpleflashlightadfree.ui.EmergencyFragment.java

/**
 * Starts emergency sound from assets/*from w w  w  .  j a  va 2s . c o  m*/
 */
public void emergencySignal() {

    try {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying() && status == FlashlightService.STATUS_OFF) {
            mMediaPlayer.stop();
            mMediaPlayer.reset();
            mMediaPlayer.release();
            mMediaPlayer = null;

            mLinearLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorBackground));
        } else if (status == FlashlightService.STATUS_BLINK) {

            final AnimationDrawable drawable = new AnimationDrawable();
            final Handler handler = new Handler();

            drawable.addFrame(new ColorDrawable(Color.RED), 400);
            drawable.addFrame(new ColorDrawable(Color.BLUE), 400);
            drawable.setOneShot(false);

            mLinearLayout.setBackground(drawable);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    drawable.start();
                }
            }, 100);

            mMediaPlayer = new MediaPlayer();
            AssetFileDescriptor descriptor = getActivity().getAssets().openFd("sews.mp3");
            mMediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(),
                    descriptor.getLength());
            descriptor.close();

            mMediaPlayer.prepare();
            mMediaPlayer.setVolume(1f, 1f);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.stanford.junction.sample.partyware.ImgurUploadService.java

/**
 * This method uploads an image from the given uri. It does the uploading in
 * small chunks to make sure it doesn't over run the memory.
 * //from w  ww .  j  ava  2  s  .  c  o m
 * @param uri
 *            image location
 * @return map containing data from interaction
 */
private String readPictureDataAndUpload(final Uri uri) {
    Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)");
    try {
        final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
        final int totalFileLength = (int) assetFileDescriptor.getLength();
        assetFileDescriptor.close();

        // Create custom progress notification
        mProgressNotification = new Notification(R.drawable.icon, getString(R.string.imgur_upload_in_progress),
                System.currentTimeMillis());
        // set as ongoing
        mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        // set custom view to notification
        mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength);
        //empty intent for the notification
        final Intent progressIntent = new Intent();
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0);
        mProgressNotification.contentIntent = contentIntent;
        // add notification to manager
        mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);

        final InputStream inputStream = getContentResolver().openInputStream(uri);

        final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis())
                + Long.toHexString((new Random()).nextLong());
        final String boundary = "--" + boundaryString;
        final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json"))
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\"");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(CHUNK_SIZE);
        final OutputStream hrout = conn.getOutputStream();
        final PrintStream hout = new PrintStream(hrout);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"key\"");
        hout.println("Content-Type: text/plain");
        hout.println();

        Random rng = new Random();
        String key = API_KEYS[rng.nextInt(API_KEYS.length)];
        hout.println(key);

        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"image\"");
        hout.println("Content-Transfer-Encoding: base64");
        hout.println();
        hout.flush();
        {
            final Base64OutputStream bhout = new Base64OutputStream(hrout);
            final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES];
            int read = 0;
            int totalRead = 0;
            long lastLogTime = 0;
            while (read >= 0) {
                read = inputStream.read(pictureData);
                if (read > 0) {
                    bhout.write(pictureData, 0, read);
                    totalRead += read;
                    if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) {
                        lastLogTime = System.currentTimeMillis();
                        Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength
                                + " bytes (" + (100 * totalRead) / totalFileLength + "%)");

                        //make a final version of the total read to make the handler happy
                        final int totalReadFinal = totalRead;
                        mHandler.post(new Runnable() {
                            public void run() {
                                mProgressNotification.contentView = generateProgressNotificationView(
                                        totalReadFinal, totalFileLength);
                                mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);
                            }
                        });
                    }
                    bhout.flush();
                    hrout.flush();
                }
            }
            Log.d(this.getClass().getName(), "Finishing upload...");
            // This close is absolutely necessary, this tells the
            // Base64OutputStream to finish writing the last of the data
            // (and including the padding). Without this line, it will miss
            // the last 4 chars in the output, missing up to 3 bytes in the
            // final output.
            bhout.close();
            Log.d(this.getClass().getName(), "Upload complete...");
            mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead,
                    false);
            mNotificationManager.cancelAll();
        }

        hout.println(boundary);
        hout.flush();
        hrout.close();

        inputStream.close();

        Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder rData = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            rData.append(line).append('\n');
        }

        return rData.toString();
    } catch (final IOException e) {
        Log.e(this.getClass().getName(), "Upload failed", e);
    }

    return null;
}

From source file:com.google.dotorg.crisisresponse.translationcards.RecordingActivity.java

private void startListening() {
    recordButton.setBackgroundResource(R.drawable.button_record_disabled);
    listenButton.setBackgroundResource(R.drawable.button_listen_active);
    recordingStatus = RecordingStatus.LISTENING;
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {/*from w  w w .  j  a v a2  s.  c o m*/
        if (isAsset) {
            AssetFileDescriptor fd = getAssets().openFd(filename);
            mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
            fd.close();
        } else {
            mediaPlayer.setDataSource(new FileInputStream(filename).getFD());
        }
        mediaPlayer.prepare();
    } catch (IOException e) {
        Log.d(TAG, "Error preparing audio.");
        throw new IllegalArgumentException(e);
        // TODO(nworden): something
    }
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            finishListening(mp);
        }
    });
    mediaPlayer.start();
}

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

/**
 * This method uploads an image from the given uri. It does the uploading in
 * small chunks to make sure it doesn't over run the memory.
 * //w w w  . j av  a  2  s .c o m
 * @param uri
 *            image location
 * @return map containing data from interaction
 */
private String readPictureDataAndUpload(final Uri uri) {
    Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)");
    try {
        final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
        final int totalFileLength = (int) assetFileDescriptor.getLength();
        assetFileDescriptor.close();

        // Create custom progress notification
        mProgressNotification = new Notification(R.drawable.icon, getString(R.string.upload_in_progress),
                System.currentTimeMillis());
        // set as ongoing
        mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        // set custom view to notification
        mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength);
        //empty intent for the notification
        final Intent progressIntent = new Intent();
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0);
        mProgressNotification.contentIntent = contentIntent;
        // add notification to manager
        mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);

        final InputStream inputStream = getContentResolver().openInputStream(uri);

        final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis())
                + Long.toHexString((new Random()).nextLong());
        final String boundary = "--" + boundaryString;
        final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json"))
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\"");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(CHUNK_SIZE);
        final OutputStream hrout = conn.getOutputStream();
        final PrintStream hout = new PrintStream(hrout);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"key\"");
        hout.println("Content-Type: text/plain");
        hout.println();
        hout.println(API_KEY);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"image\"");
        hout.println("Content-Transfer-Encoding: base64");
        hout.println();
        hout.flush();
        {
            final Base64OutputStream bhout = new Base64OutputStream(hrout);
            final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES];
            int read = 0;
            int totalRead = 0;
            long lastLogTime = 0;
            while (read >= 0) {
                read = inputStream.read(pictureData);
                if (read > 0) {
                    bhout.write(pictureData, 0, read);
                    totalRead += read;
                    if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) {
                        lastLogTime = System.currentTimeMillis();
                        Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength
                                + " bytes (" + (100 * totalRead) / totalFileLength + "%)");

                        //make a final version of the total read to make the handler happy
                        final int totalReadFinal = totalRead;
                        mHandler.post(new Runnable() {
                            public void run() {
                                mProgressNotification.contentView = generateProgressNotificationView(
                                        totalReadFinal, totalFileLength);
                                mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);
                            }
                        });
                    }
                    bhout.flush();
                    hrout.flush();
                }
            }
            Log.d(this.getClass().getName(), "Finishing upload...");
            // This close is absolutely necessary, this tells the
            // Base64OutputStream to finish writing the last of the data
            // (and including the padding). Without this line, it will miss
            // the last 4 chars in the output, missing up to 3 bytes in the
            // final output.
            bhout.close();
            Log.d(this.getClass().getName(), "Upload complete...");
            mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead,
                    false);
        }

        hout.println(boundary);
        hout.flush();
        hrout.close();

        inputStream.close();

        Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder rData = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            rData.append(line).append('\n');
        }

        return rData.toString();
    } catch (final IOException e) {
        Log.e(this.getClass().getName(), "Upload failed", e);
    }

    return null;
}