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:se.droidgiro.scanner.CaptureActivity.java

/**
 * Creates the beep MediaPlayer in advance so that the sound can be
 * triggered with the least latency possible.
 *///from ww w .j a  v a 2 s.com
private void initBeepSound() {
    if (playBeep && mediaPlayer == null) {
        // The volume on STREAM_SYSTEM is not adjustable, and users found it
        // too loud,
        // so we now play on the music stream.
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnCompletionListener(beepListener);

        AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
            file.close();
            mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
            mediaPlayer.prepare();
        } catch (IOException e) {
            mediaPlayer = null;
        }
    }
}

From source file:eu.sathra.io.IO.java

public <T> T load(AssetFileDescriptor afd, Class<T> clazz) throws Exception {

    BufferedReader reader = new BufferedReader(new InputStreamReader(afd.createInputStream(), "UTF-8"));

    // do reading, usually loop until end of file reading
    String line;//from   www  .  j a v  a  2s . co m
    StringBuilder myBuilder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        myBuilder.append(line);
    }

    reader.close();
    afd.close();

    return load(myBuilder.toString(), clazz);
}

From source file:org.mercycorps.translationcards.activity.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 .  ja  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();
        }
    });
    mediaPlayer.start();
}

From source file:org.awesomeapp.messenger.ui.ConversationListItem.java

/**
    public void bind(ConversationViewHolder holder, Cursor cursor, String underLineText, boolean scrolling) {
bind(holder, cursor, underLineText, true, scrolling);
    }// w w w .  j  a v a 2  s.  co m
*/

public void bind(ConversationViewHolder holder, long contactId, long providerId, long accountId, String address,
        String nickname, int contactType, String message, long messageDate, int presence, String underLineText,
        boolean showChatMsg, boolean scrolling) {

    //applyStyleColors(holder);

    if (nickname == null) {
        nickname = address.split("@")[0].split("\\.")[0];
    } else {
        nickname = nickname.split("@")[0].split("\\.")[0];
    }

    if (Imps.Contacts.TYPE_GROUP == contactType) {

        String groupCountString = getGroupCount(getContext().getContentResolver(), contactId);
        nickname += groupCountString;
    }

    if (!TextUtils.isEmpty(underLineText)) {
        // highlight/underline the word being searched 
        String lowercase = nickname.toLowerCase();
        int start = lowercase.indexOf(underLineText.toLowerCase());
        if (start >= 0) {
            int end = start + underLineText.length();
            SpannableString str = new SpannableString(nickname);
            str.setSpan(new UnderlineSpan(), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

            holder.mLine1.setText(str);

        } else
            holder.mLine1.setText(nickname);

    } else
        holder.mLine1.setText(nickname);

    holder.mStatusIcon.setVisibility(View.GONE);

    if (holder.mAvatar != null) {
        if (Imps.Contacts.TYPE_GROUP == contactType) {

            holder.mAvatar.setVisibility(View.VISIBLE);

            if (AVATAR_DEFAULT_GROUP == null)
                AVATAR_DEFAULT_GROUP = new RoundedAvatarDrawable(
                        BitmapFactory.decodeResource(getResources(), R.drawable.group_chat));

            holder.mAvatar.setImageDrawable(AVATAR_DEFAULT_GROUP);

        }
        //   else if (cursor.getColumnIndex(Imps.Contacts.AVATAR_DATA)!=-1)
        else {
            //                holder.mAvatar.setVisibility(View.GONE);

            Drawable avatar = null;

            try {
                avatar = DatabaseUtils.getAvatarFromAddress(this.getContext().getContentResolver(), address,
                        ImApp.SMALL_AVATAR_WIDTH, ImApp.SMALL_AVATAR_HEIGHT);
                // avatar = DatabaseUtils.getAvatarFromCursor(cursor, COLUMN_AVATAR_DATA, ImApp.SMALL_AVATAR_WIDTH, ImApp.SMALL_AVATAR_HEIGHT);
            } catch (Exception e) {
                //problem decoding avatar
                Log.e(ImApp.LOG_TAG, "error decoding avatar", e);
            }

            try {
                if (avatar != null) {
                    //if (avatar instanceof RoundedAvatarDrawable)
                    //  setAvatarBorder(presence,(RoundedAvatarDrawable)avatar);

                    holder.mAvatar.setImageDrawable(avatar);
                } else {
                    // int color = getAvatarBorder(presence);
                    int padding = 24;
                    LetterAvatar lavatar = new LetterAvatar(getContext(), nickname, padding);

                    holder.mAvatar.setImageDrawable(lavatar);

                }

                holder.mAvatar.setVisibility(View.VISIBLE);
            } catch (OutOfMemoryError ome) {
                //this seems to happen now and then even on tiny images; let's catch it and just not set an avatar
            }

        }
    }

    if (showChatMsg && message != null) {

        if (holder.mLine2 != null) {
            if (SecureMediaStore.isVfsUri(message)) {
                FileInfo fInfo = SystemServices.getFileInfoFromURI(getContext(), Uri.parse(message));

                if (fInfo.type == null || fInfo.type.startsWith("image")) {

                    if (holder.mMediaThumb != null) {
                        holder.mMediaThumb.setVisibility(View.VISIBLE);

                        if (fInfo.type != null && fInfo.type.equals("image/png")) {
                            holder.mMediaThumb.setScaleType(ImageView.ScaleType.FIT_CENTER);
                        } else {
                            holder.mMediaThumb.setScaleType(ImageView.ScaleType.CENTER_CROP);

                        }

                        setThumbnail(getContext().getContentResolver(), holder, Uri.parse(message));

                        holder.mLine2.setVisibility(View.GONE);

                    }
                } else {
                    holder.mLine2.setText("");
                }

            } else if ((!TextUtils.isEmpty(message)) && message.startsWith("/")) {
                String cmd = message.toString().substring(1);

                if (cmd.startsWith("sticker")) {
                    String[] cmds = cmd.split(":");

                    String mimeTypeSticker = "image/png";
                    Uri mediaUri = Uri.parse("asset://" + cmds[1]);

                    setThumbnail(getContext().getContentResolver(), holder, mediaUri);
                    holder.mLine2.setVisibility(View.GONE);

                    holder.mMediaThumb.setScaleType(ImageView.ScaleType.FIT_CENTER);

                }

            } else if ((!TextUtils.isEmpty(message)) && message.startsWith(":")) {
                String[] cmds = message.split(":");

                try {
                    String[] stickerParts = cmds[1].split("-");
                    String stickerPath = "stickers/" + stickerParts[0].toLowerCase() + "/"
                            + stickerParts[1].toLowerCase() + ".png";

                    //make sure sticker exists
                    AssetFileDescriptor afd = getContext().getAssets().openFd(stickerPath);
                    afd.getLength();
                    afd.close();

                    //now setup the new URI for loading local sticker asset
                    Uri mediaUri = Uri.parse("asset://localhost/" + stickerPath);
                    setThumbnail(getContext().getContentResolver(), holder, mediaUri);
                    holder.mLine2.setVisibility(View.GONE);
                    holder.mMediaThumb.setScaleType(ImageView.ScaleType.FIT_CENTER);

                } catch (Exception e) {

                }
            } else {
                if (holder.mMediaThumb != null)
                    holder.mMediaThumb.setVisibility(View.GONE);

                holder.mLine2.setVisibility(View.VISIBLE);

                try {
                    holder.mLine2.setText(android.text.Html.fromHtml(message).toString());
                } catch (RuntimeException re) {
                }
            }
        }

        if (messageDate != -1) {
            Date dateLast = new Date(messageDate);
            holder.mStatusText.setText(sPrettyTime.format(dateLast));

        } else {
            holder.mStatusText.setText("");
        }

    } else if (holder.mLine2 != null) {
        holder.mLine2.setText(address);

        if (holder.mMediaThumb != null)
            holder.mMediaThumb.setVisibility(View.GONE);
    }

    holder.mLine1.setVisibility(View.VISIBLE);

    if (providerId != -1)
        getEncryptionState(providerId, accountId, address, holder);
}

From source file:com.eggwall.SoundSleep.AudioService.java

/**
 * Start playing the resource specified here.
 *
 * @param type Either MUSIC, or WHITE_NOISE. Passing the same ID twice
 *             is a signal to stop playing music altogether.
 *//*www .java 2 s  .com*/
private void play(int type) {
    if (type == MUSIC) {
        final MediaPlayer player = tryStartingMusic();
        if (player != null) {
            mPlayer = player;
            mPlayer.prepareAsync();
            // onPrepared will get called when the media player is ready to play.
            return;
        }
    }
    // Either we weren't able to play custom music, or we were asked to play white noise.
    final int resourceToPlay;
    if (type == WHITE_NOISE) {
        Log.v(TAG, "Playing white noise.");
        resourceToPlay = R.raw.noise;
    } else {
        Log.v(TAG, "Playing included jingle.");
        resourceToPlay = R.raw.jingle;
    }
    try {
        final AssetFileDescriptor d = getResources().openRawResourceFd(resourceToPlay);
        if (d == null) {
            Log.wtf(TAG, "Could not open the file to play");
            return;
        }
        final FileDescriptor fd = d.getFileDescriptor();
        mPlayer = getGenericMediaPlayer();
        mPlayer.setDataSource(fd, d.getStartOffset(), d.getLength());
        d.close();
        // White noise or the default song is looped forever.
        mPlayer.setLooping(true);
    } catch (IOException e) {
        Log.e(TAG, "Could not create a media player instance. Full error below.");
        e.printStackTrace();
        return;
    }
    postSuccessMessage(mTypePlaying);
    mPlayer.prepareAsync();
}

From source file:io.github.carlorodriguez.morningritual.MainActivity.java

private void playLegacyNotificationSound() throws IOException {
    AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.sound);

    if (afd == null)
        throw new IOException();

    if (mMediaPlayer != null) {
        mMediaPlayer.release();//from www.  j  av  a2 s  . c om
    }

    mMediaPlayer = new MediaPlayer();

    mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());

    afd.close();

    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

    mMediaPlayer.prepare();

    mMediaPlayer.start();
}

From source file:android.widget.TiVideoView4.java

private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
        // not ready for playback just yet, will try again later
        return;//w  w w . ja va  2s . co m
    }
    // Tell the music playback service to pause
    // TODO: these constants need to be published somewhere in the framework.
    Intent i = new Intent("com.android.music.musicservicecommand");
    i.putExtra("command", "pause");
    getContext().sendBroadcast(i);

    if (mMediaPlayer != null) {
        mMediaPlayer.reset();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
    try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mIsPrepared = false;
        Log.v(TAG, "reset duration to -1 in openVideo");
        mDuration = -1;
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mCurrentBufferPercentage = 0;
        if (URLUtil.isAssetUrl(mUri.toString())) { // DST: 20090606 detect asset url
            AssetFileDescriptor afd = null;
            try {
                String path = mUri.toString().substring("file:///android_asset/".length());
                afd = getContext().getAssets().openFd(path);
                mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            } finally {
                if (afd != null) {
                    afd.close();
                }
            }
        } else {
            setDataSource();
        }
        mMediaPlayer.setDisplay(mSurfaceHolder);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);
        mMediaPlayer.prepareAsync();
        attachMediaController();
    } catch (IOException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        return;
    } catch (IllegalArgumentException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        return;
    }
}

From source file:org.awesomeapp.messenger.ui.MessageListItem.java

public void bindOutgoingMessage(MessageViewHolder holder, int id, int messageType, String address,
        final String mimeType, final String body, Date date, Markup smileyRes, boolean scrolling,
        DeliveryState delivery, EncryptionState encryption) {

    mHolder = holder;/*  w  ww .  j  a v a 2 s.co m*/
    applyStyleColors();

    mHolder.mTextViewForMessages.setVisibility(View.VISIBLE);
    mHolder.mAudioContainer.setVisibility(View.GONE);
    mHolder.mMediaContainer.setVisibility(View.GONE);
    mHolder.mAudioButton.setImageResource(R.drawable.media_audio_play);

    mHolder.resetOnClickListenerMediaThumbnail();

    lastMessage = body;

    if (mimeType != null) {

        lastMessage = "";

        Uri mediaUri = Uri.parse(body);

        if (mimeType.startsWith("audio")) {
            try {
                mHolder.mAudioContainer.setVisibility(View.VISIBLE);
                showAudioPlayer(mimeType, mediaUri, id, mHolder);
            } catch (Exception e) {
                mHolder.mAudioContainer.setVisibility(View.GONE);
            }

        } else {
            mHolder.mTextViewForMessages.setVisibility(View.GONE);

            mHolder.mMediaContainer.setVisibility(View.VISIBLE);
            showMediaThumbnail(mimeType, mediaUri, id, mHolder);

        }

    } else if ((!TextUtils.isEmpty(lastMessage))
            && (lastMessage.charAt(0) == '/' || lastMessage.charAt(0) == ':')) {
        //            String cmd = lastMessage.toString().substring(1);
        boolean cmdSuccess = false;

        if (lastMessage.startsWith("/sticker:")) {
            String[] cmds = lastMessage.split(":");

            String mimeTypeSticker = "image/png";
            try {
                //make sure sticker exists
                AssetFileDescriptor afd = getContext().getAssets().openFd(cmds[1]);
                afd.getLength();
                afd.close();

                //now setup the new URI for loading local sticker asset
                Uri mediaUri = Uri.parse("asset://localhost/" + cmds[1].toLowerCase());

                //now load the thumbnail
                cmdSuccess = showMediaThumbnail(mimeTypeSticker, mediaUri, id, mHolder);
            } catch (Exception e) {
                cmdSuccess = false;
            }

        } else if (lastMessage.startsWith(":")) {
            String[] cmds = lastMessage.split(":");

            String mimeTypeSticker = "image/png";
            try {
                String[] stickerParts = cmds[1].split("-");
                String stickerPath = "stickers/" + stickerParts[0].toLowerCase() + "/"
                        + stickerParts[1].toLowerCase() + ".png";

                //make sure sticker exists
                AssetFileDescriptor afd = getContext().getAssets().openFd(stickerPath);
                afd.getLength();
                afd.close();

                //now setup the new URI for loading local sticker asset
                Uri mediaUri = Uri.parse("asset://localhost/" + stickerPath);

                //now load the thumbnail
                cmdSuccess = showMediaThumbnail(mimeTypeSticker, mediaUri, id, mHolder);
            } catch (Exception e) {
                cmdSuccess = false;
            }
        }

        if (!cmdSuccess) {
            mHolder.mTextViewForMessages.setText(new SpannableString(lastMessage));
        } else {
            holder.mContainer.setBackgroundResource(android.R.color.transparent);
            lastMessage = "";
        }

    } else {
        mHolder.mTextViewForMessages.setText(new SpannableString(lastMessage));
    }

    //if (isSelected())
    //  mHolder.mContainer.setBackgroundColor(getResources().getColor(R.color.holo_blue_bright));

    if (date != null) {

        CharSequence tsText = formatTimeStamp(date, messageType, delivery, encryption, null);

        mHolder.mTextViewForTimestamp.setText(tsText);

        mHolder.mTextViewForTimestamp.setVisibility(View.VISIBLE);

    } else {
        mHolder.mTextViewForTimestamp.setText("");

    }
    if (linkify)
        LinkifyHelper.addLinks(mHolder.mTextViewForMessages, new URLSpanConverter());
    LinkifyHelper.addTorSafeLinks(mHolder.mTextViewForMessages);
}

From source file:org.awesomeapp.messenger.ui.MessageListItem.java

public void bindIncomingMessage(MessageViewHolder holder, int id, int messageType, String address,
        String nickname, final String mimeType, final String body, Date date, Markup smileyRes,
        boolean scrolling, EncryptionState encryption, boolean showContact, int presenceStatus) {

    mHolder = holder;//w w  w.  j  av  a 2s  .c o  m
    applyStyleColors();
    mHolder.mTextViewForMessages.setVisibility(View.VISIBLE);
    mHolder.mAudioContainer.setVisibility(View.GONE);
    mHolder.mMediaContainer.setVisibility(View.GONE);

    if (nickname == null)
        nickname = address;

    lastMessage = formatMessage(body);
    showAvatar(address, nickname, true, presenceStatus);

    mHolder.resetOnClickListenerMediaThumbnail();

    if (mimeType != null) {

        Uri mediaUri = Uri.parse(body);
        lastMessage = "";

        if (mimeType.startsWith("audio")) {
            mHolder.mAudioButton.setImageResource(R.drawable.media_audio_play);

            try {
                mHolder.mAudioContainer.setVisibility(View.VISIBLE);
                showAudioPlayer(mimeType, mediaUri, id, mHolder);
            } catch (Exception e) {
                mHolder.mAudioContainer.setVisibility(View.GONE);
            }

        } else {
            mHolder.mTextViewForMessages.setVisibility(View.GONE);

            showMediaThumbnail(mimeType, mediaUri, id, mHolder);

            mHolder.mMediaContainer.setVisibility(View.VISIBLE);

        }

    } else if ((!TextUtils.isEmpty(lastMessage))
            && (lastMessage.charAt(0) == '/' || lastMessage.charAt(0) == ':')) {
        boolean cmdSuccess = false;

        if (lastMessage.startsWith("/sticker:")) {
            String[] cmds = lastMessage.split(":");

            String mimeTypeSticker = "image/png";

            try {

                String assetPath = cmds[1].split(" ")[0].toLowerCase();//just get up to any whitespace;

                //make sure sticker exists
                AssetFileDescriptor afd = getContext().getAssets().openFd(assetPath);
                afd.getLength();
                afd.close();

                //now setup the new URI for loading local sticker asset
                Uri mediaUri = Uri.parse("asset://localhost/" + assetPath);

                //now load the thumbnail
                cmdSuccess = showMediaThumbnail(mimeTypeSticker, mediaUri, id, mHolder);
            } catch (Exception e) {
                Log.e(ImApp.LOG_TAG, "error loading sticker bitmap: " + cmds[1], e);
                cmdSuccess = false;
            }

        } else if (lastMessage.startsWith(":")) {
            String[] cmds = lastMessage.split(":");

            String mimeTypeSticker = "image/png";
            try {
                String[] stickerParts = cmds[1].split("-");
                String stickerPath = "stickers/" + stickerParts[0].toLowerCase() + "/"
                        + stickerParts[1].toLowerCase() + ".png";

                //make sure sticker exists
                AssetFileDescriptor afd = getContext().getAssets().openFd(stickerPath);
                afd.getLength();
                afd.close();

                //now setup the new URI for loading local sticker asset
                Uri mediaUri = Uri.parse("asset://localhost/" + stickerPath);

                //now load the thumbnail
                cmdSuccess = showMediaThumbnail(mimeTypeSticker, mediaUri, id, mHolder);
            } catch (Exception e) {
                cmdSuccess = false;
            }
        }

        if (!cmdSuccess) {
            mHolder.mTextViewForMessages.setText(new SpannableString(lastMessage));
        } else {
            mHolder.mContainer.setBackgroundResource(android.R.color.transparent);
            lastMessage = "";
        }

    }

    //  if (isSelected())
    //    mHolder.mContainer.setBackgroundColor(getResources().getColor(R.color.holo_blue_bright));

    if (lastMessage.length() > 0) {
        mHolder.mTextViewForMessages.setText(new SpannableString(lastMessage));
    } else {
        mHolder.mTextViewForMessages.setText(lastMessage);
    }

    if (date != null) {

        String contact = null;
        if (showContact) {
            String[] nickParts = nickname.split("/");
            contact = nickParts[nickParts.length - 1];
        }

        CharSequence tsText = formatTimeStamp(date, messageType, null, encryption, contact);

        mHolder.mTextViewForTimestamp.setText(tsText);
        mHolder.mTextViewForTimestamp.setVisibility(View.VISIBLE);

    } else {

        mHolder.mTextViewForTimestamp.setText("");
        //mHolder.mTextViewForTimestamp.setVisibility(View.GONE);

    }
    if (linkify)
        LinkifyHelper.addLinks(mHolder.mTextViewForMessages, new URLSpanConverter());
    LinkifyHelper.addTorSafeLinks(mHolder.mTextViewForMessages);
}

From source file:inc.bait.jubilee.ui.fragments.ContactsListFragment.java

private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {
    if (!isAdded() || getActivity() == null) {
        return null;
    }/*from ww  w .j a va2 s .co  m*/
    AssetFileDescriptor afd = null;
    try {
        Uri thumbUri;
        if (ApiHelper.hasHoneycomb()) {
            thumbUri = Uri.parse(photoData);
        } else {
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);
            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }
        afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");
        FileDescriptor fileDescriptor = afd.getFileDescriptor();

        if (fileDescriptor != null) {
            return ImgLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData + ": " + e.toString());
        }
    } finally {
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}