Example usage for android.content.res AssetFileDescriptor getLength

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

Introduction

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

Prototype

public long getLength() 

Source Link

Document

Returns the total number of bytes of this asset entry's data.

Usage

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 ww  w.  j av a 2 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);
    }// www.  j  a  v a  2 s  .  com
*/

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.
 *//*from   ww  w  .ja v  a  2  s  .c o m*/
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:org.opendatakit.tables.tasks.InitializeTask.java

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

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

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

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

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

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

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

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

From source file: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 w  w  w . j a  v a 2  s . c  o m
    }

    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:com.intel.xdk.player.Player.java

public void startAudio(String strRelativeFileURL, boolean shouldLoop) {
    if (isPlayingPodcast()) {
        injectJS(//from   ww  w.j  a v  a 2 s. co m
                "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.player.audio.busy',true,true);document.dispatchEvent(ev);");
        return;
    } else if (isPlayingAudio()) {
        stopAudio();
    }

    soundName = strRelativeFileURL;
    Object path = pathToFile(strRelativeFileURL);

    try {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
        } catch (Exception e) {
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setLooping(shouldLoop);
        mediaPlayer.setOnErrorListener(soundOnError);
        mediaPlayer.setOnCompletionListener(soundOnComplete);

        //set data source based on type
        if (path instanceof AssetFileDescriptor) {
            try {
                AssetFileDescriptor afd = ((AssetFileDescriptor) path);
                mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            File file = new File((String) path);
            try {
                FileInputStream fis = new FileInputStream(file);
                mediaPlayer.setDataSource(fis.getFD());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        mediaPlayer.prepare();
        mediaPlayer.seekTo(audioTime);
        mediaPlayer.setVolume(audioVolume, audioVolume);
        mediaPlayer.start();
    } catch (Exception e) {
        injectJS(
                "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.player.audio.error',true,true);document.dispatchEvent(ev);");
        return;
    }

    //activity.trackPageView("/intel.xdk.podcast." + getAudioName(soundName) + ".stop");

    setPlayingAudio(true);
    injectJS(
            "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.player.audio.start');document.dispatchEvent(ev);");
}

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

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

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

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

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

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

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

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 ww.jav  a 2  s.c  o 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:com.commontime.cordova.audio.AudioPlayer.java

/**
 * load audio file//from   w  ww  .  j  a  v  a  2  s. c  o m
 * @throws IOException
 * @throws IllegalStateException
 * @throws SecurityException
 * @throws IllegalArgumentException
 */
private void loadAudioFile(String file)
        throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
    if (this.isStreaming(file)) {
        this.player.setDataSource(file);
        this.player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        //if it's a streaming file, play mode is implied
        this.setMode(MODE.PLAY);
        this.setState(STATE.MEDIA_STARTING);
        this.player.setOnPreparedListener(this);
        this.player.prepareAsync();
    } else {
        if (file.startsWith("/android_asset/")) {
            String f = file.substring(15);
            android.content.res.AssetFileDescriptor fd = this.handler.cordova.getActivity().getAssets()
                    .openFd(f);
            this.player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
        } else {
            File fp = new File(file);
            if (fp.exists()) {
                FileInputStream fileInputStream = new FileInputStream(file);
                this.player.setDataSource(fileInputStream.getFD());
                fileInputStream.close();
            } else {
                this.player.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/" + file);
            }
        }
        this.setState(STATE.MEDIA_STARTING);
        this.player.setOnPreparedListener(this);
        this.player.prepare();

        // Get duration
        this.duration = getDurationInSeconds();
    }
}

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  w  w . j ava  2 s.c  om
    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);
}