Example usage for android.media MediaPlayer prepare

List of usage examples for android.media MediaPlayer prepare

Introduction

In this page you can find the example usage for android.media MediaPlayer prepare.

Prototype

public void prepare() throws IOException, IllegalStateException 

Source Link

Document

Prepares the player for playback, synchronously.

Usage

From source file:com.ringdroid.RingdroidEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename);
    mTitle = metadataReader.mTitle;//from ww  w.  j av  a  2 s.  c  o m
    mArtist = metadataReader.mArtist;
    mAlbum = metadataReader.mAlbum;
    mYear = metadataReader.mYear;
    mGenre = metadataReader.mGenre;

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(Utils.convertGBK(titleLabel));

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(RingdroidEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));

            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            mProgressDialog.dismiss();
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                e.printStackTrace();

                Runnable runnable = new Runnable() {
                    public void run() {
                        mProgressDialog.dismiss();
                        mInfo.setText(e.toString());
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    mProgressDialog.dismiss();
                }

            });
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                RingdroidEditActivity.this.finish();
            }
        }
    }.start();
}

From source file:mobi.omegacentauri.ptimer.PTimerEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename);
    mTitle = metadataReader.mTitle;/*  ww w .  ja  v  a 2s. c o  m*/
    mArtist = metadataReader.mArtist;
    mAlbum = metadataReader.mAlbum;
    mYear = metadataReader.mYear;
    mGenre = metadataReader.mGenre;

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(titleLabel);

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(PTimerEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));

            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    mProgressDialog.dismiss();
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                mProgressDialog.dismiss();
                e.printStackTrace();
                mInfo.setText(e.toString());

                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mProgressDialog.dismiss();
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                PTimerEditActivity.this.finish();
            }
        }
    }.start();
}

From source file:com.SpeechEd.SpeechEdEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename);
    mTitle = metadataReader.mTitle;/*from w  w w. j  a v a2s.  co  m*/
    mArtist = metadataReader.mArtist;
    mAlbum = metadataReader.mAlbum;
    mYear = metadataReader.mYear;
    mGenre = metadataReader.mGenre;

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(titleLabel);

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(SpeechEdEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));

            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    mProgressDialog.dismiss();
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                mProgressDialog.dismiss();
                e.printStackTrace();
                mInfo.setText(e.toString());

                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mProgressDialog.dismiss();
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                SpeechEdEditActivity.this.finish();
            }
        }
    }.start();
}

From source file:com.PPRZonDroid.MainActivity.java

/**
 * Play warning sound if airspeed goes below the selected value
 *
 * @param context/*from  w  w  w .j  ava2 s . co m*/
 * @throws IllegalArgumentException
 * @throws SecurityException
 * @throws IllegalStateException
 * @throws IOException
 */
public void play_sound(Context context)
        throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {

    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    MediaPlayer mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setDataSource(context, soundUri);
    final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    //Set volume max!!!
    audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM,
            audioManager.getStreamMaxVolume(audioManager.STREAM_SYSTEM), 0);

    if (audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM) != 0) {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
        mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    }
}

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

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

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

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

From source file:com.Beat.RingdroidEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    /* SongMetadataReader metadataReader = new SongMetadataReader(
    this, mFilename);//from  w  ww.  j  ava2s .co  m
     mTitle = metadataReader.mTitle;
     mArtist = metadataReader.mArtist;
     mAlbum = metadataReader.mAlbum;
     mYear = metadataReader.mYear;
     mGenre = metadataReader.mGenre;*/

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(titleLabel);

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(RingdroidEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));
            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    mProgressDialog.dismiss();
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                mProgressDialog.dismiss();
                e.printStackTrace();
                mInfo.setText(e.toString());

                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mProgressDialog.dismiss();
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                RingdroidEditActivity.this.finish();
            }
        }
    }.start();
}

From source file:com.quwu.xinwo.release.Release_Activity.java

/**
 * //from   w ww.  java  2  s  .c  om
 * */
private void isPlayRecording() {
    MediaPlayer mPlayer = null;
    long duration = 0;
    mPlayer = new MediaPlayer();
    MediaPlayer mp = MediaPlayer.create(Release_Activity.this, Uri.parse(path));
    if (mp != null) {
        duration = mp.getDuration() / 1000;
    }
    try {
        mPlayer.setDataSource(path);
        mPlayer.prepare();
        mPlayer.start();
    } catch (IOException e) {
    }
    String str = duration % 60 + "";
    playerBtn.setText(str + "s");
}

From source file:org.kontalk.ui.AbstractComposeFragment.java

private boolean prepareAudio(File audioFile, final AudioContentViewControl view, final long messageId) {
    stopMediaPlayerUpdater();//from ww  w . j a v a  2 s.c  o  m
    try {
        AudioFragment audio = getAudioFragment();
        final MediaPlayer player = audio.getPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource(audioFile.getAbsolutePath());
        player.prepare();

        // prepare was successful
        audio.setMessageId(messageId);
        mAudioControl = view;

        view.prepare(player.getDuration());
        player.seekTo(view.getPosition());
        view.setProgressChangeListener(true);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopMediaPlayerUpdater();
                view.end();
                AudioFragment audio = getAudioFragment();
                if (audio != null) {
                    // this is mainly to get the wake lock released
                    audio.pausePlaying();
                    audio.seekPlayerTo(0);
                }
                setAudioStatus(AudioContentView.STATUS_ENDED);
            }
        });
        return true;
    } catch (IOException e) {
        Toast.makeText(getActivity(), R.string.err_file_not_found, Toast.LENGTH_SHORT).show();
        return false;
    }
}

From source file:com.stikyhive.stikyhive.ChattingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().setBackgroundDrawableResource(R.drawable.chat_bg);
    // this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    recipientStkid = getIntent().getExtras().getString("recipientStkid");
    chatRecipient = getIntent().getExtras().getString("chatRecipient");
    chatRecipientUrl = getIntent().getExtras().getString("chatRecipientUrl");
    senderToken = getIntent().getExtras().getString("senderToken");
    recipientToken = getIntent().getExtras().getString("recipientToken");
    noti = getIntent().getExtras().getBoolean("noti");
    message = getIntent().getExtras().getString("message");
    rows = getIntent().getExtras().getInt("rows");
    flagChatting = true;/*  w ww .  j  ava 2 s.  c  o m*/
    pref = PreferenceManager.getDefaultSharedPreferences(this);
    offerId = 0;
    offerStatus = 0;
    ws = new JsonWebService();
    dbHelper = new DBHelper(this);
    dialog = new ProgressDialog(this);
    listChatContact = new ArrayList<>();
    listChatContact = dbHelper.getChatContact();
    Log.i(" Chat Contact ", " " + listChatContact.size());
    metrics = this.getResources().getDisplayMetrics();
    //to change font
    faceSemi_bold = Typeface.createFromAsset(getAssets(), fontOSSemi_bold);
    Typeface faceLight = Typeface.createFromAsset(getAssets(), fontOSLight);
    faceRegular = Typeface.createFromAsset(getAssets(), fontOSRegular);

    imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited()) {
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
    }

    start = new Date();
    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
    timeSend = oFormat.format(start);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);

    layoutTalk = (LinearLayout) findViewById(R.id.layoutTalk);
    txtUserName = (TextView) findViewById(R.id.txtChatName);
    edTxtMsg = (EditText) findViewById(R.id.edTxtMsg);
    imgViewProfile = (ImageView) findViewById(R.id.imgViewChat);
    imgViewAddCon = (ImageView) findViewById(R.id.imgAddContact);
    lv = (ListView) findViewById(R.id.listView1);
    layoutLabel = (LinearLayout) findViewById(R.id.layoutLabel);
    txtLabel1 = (TextView) findViewById(R.id.txtLabel1);
    txtLabel2 = (TextView) findViewById(R.id.txtLabel2);
    txtLabel3 = (TextView) findViewById(R.id.txtLabel3);
    txtLabel2.setText(" " + chatRecipient + " ");
    txtLabel1.setTypeface(faceLight);
    txtLabel2.setTypeface(faceRegular);
    txtLabel3.setTypeface(faceLight);

    for (ChatContact contact : listChatContact) {
        if (contact.getContactId().equals(recipientStkid)) {
            imgViewAddCon.setVisibility(View.INVISIBLE);
            layoutLabel.setVisibility(View.GONE);
            break;
        }
    }
    Log.i(TAG, " come back again");
    adapter = new ChatArrayAdapter(this, R.layout.chatting_listview, faceSemi_bold, faceRegular, recipientStkid,
            senderToken, recipientToken);
    lv.setAdapter(adapter);
    // adapter.add(new StikyChat(chatRecipientUrl, "Hello", false, "12.10.2015", "12.1.2014"));

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    // BEGIN_INCLUDE (change_colors)
    // Set the color scheme of the SwipeRefreshLayout by providing 4 color resource ids
    swipeRefreshLayout.setColorScheme(R.color.swipe_color_1, R.color.swipe_color_2, R.color.swipe_color_3,
            R.color.swipe_color_4);
    limitMsg = 7;
    // END_INCLUDE (change_colors)
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.i(" Refresh Layout ", "onRefresh called from SwipeRefreshLayout");
            if (limitMsg < rows) {
                Log.i("Limit Message ", " " + limitMsg);
                limitMsg *= 2;
                fetchRecords();
            } else if ((!(rows <= 7)) && limitMsg > rows && (limitMsg - rows < 7)) {
                fetchRecords();
            } else {
                Log.i("No data ", "to refresh");
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getApplicationContext(), "No data to refresh!", Toast.LENGTH_SHORT).show();
            }
            // initiateRefresh();
        }
    });

    LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout headerLayout = (LinearLayout) findViewById(R.id.header);
    View header = inflator.inflate(R.layout.header, null);

    TextView textView = (TextView) header.findViewById(R.id.textView1);
    textView.setText("StikyChat");
    textView.setTypeface(faceSemi_bold);
    textView.setVisibility(View.VISIBLE);
    headerLayout.addView(header);
    LinearLayout layoutRight = (LinearLayout) header.findViewById(R.id.layoutRight);
    layoutRight.setVisibility(View.GONE);

    txtUserName.setText(chatRecipient);
    Log.i(TAG, "Activity Name " + txtUserName.getText().toString());
    txtUserName.setTypeface(faceSemi_bold);

    String url = "";

    Log.i(TAG, " ^^^ " + chatRecipientUrl + " ");
    if (chatRecipientUrl != null) {
        if (chatRecipientUrl.contains("http")) {
            url = chatRecipientUrl;
        } else if (chatRecipientUrl != "null") {
            url = this.getResources().getString(R.string.url) + "/" + chatRecipientUrl;
        }
    }
    addAndroidUniversalImageLoader(imgViewProfile, url);
    //        if (noti && (!message.equals(""))) {
    //            adapter.add(new StikyChat(chatRecipientUrl, message, true, timeSend, ""));
    //            lv.smoothScrollToPosition(adapter.getCount() - 1);
    //        }

    //to show history chats between two users(sender & recipient)
    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat2 = new SimpleDateFormat("dd MMM HH:mm");
    listHistory = dbHelper.getStikyChat();
    if (listHistory.size() > 0) {
        Collections.reverse(listHistory);
        for (final StikyChatTb chatTb : listHistory) {
            String getDate = chatTb.getSendDate();
            String durationStr = null;
            String fromStikyBee = chatTb.getSender();
            try {
                final String createDate = dateFormat2.format(dateFormat.parse(getDate));
                if (chatTb.getFileName().contains("voice")) {
                    MediaPlayer mPlayer = new MediaPlayer();
                    String voiceFileName = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    try {
                        mPlayer.setDataSource(voiceFileName);
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //mPlayer.start();
                    int duration = mPlayer.getDuration();
                    mPlayer.release();
                    duration = (int) Math.ceil(duration / 1024);

                    if (duration < 10) {
                        durationStr = "00:0" + duration;
                    } else {
                        durationStr = "00:" + duration;
                    }
                    // Log.i(TAG, "Duration Srt " + durationStr);
                }
                if (fromStikyBee.equals(pref.getString("stkid", ""))) {
                    //String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    // Log.i(TAG, " Offer Id " + chatTb.getOfferId() + " Price " + chatTb.getPrice() + " Name " + chatTb.getName());
                    //first false = right, second false = Offer
                    //  Log.i(TAG, " Duration " + chatTb.getRate() + " File Name " + chatTb.getFileName());
                    if (!chatTb.getFileName().contains("voice")) {
                        Log.i(TAG, " Voice is not ");
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                chatTb.getOriFName()));
                    } else {
                        Log.i(TAG, " Voice is ");
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                    }
                } else {
                    /* Bitmap bmImg = BitmapFactory.decodeFile(getResources().getString(R.string.url) + "/" + chatTb.getFileName());
                     Bitmap resBm = getResizedBitmap(bmImg, 500);*/
                    // String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    if (!chatTb.getFileName().contains("voice")) {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                chatTb.getOriFName()));
                    } else {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                    }
                }
                lv.smoothScrollToPosition(adapter.getCount() - 1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            fileNameGCM = sharedPreferences.getString("fileName", "");
            messageGCM = sharedPreferences.getString("message", "");
            offerIdGCM = sharedPreferences.getInt("offerId", 0);
            offerStatusGCM = sharedPreferences.getInt("offerStatus", 0);
            priceGCM = sharedPreferences.getString("price", "");
            rateGCM = sharedPreferences.getString("rate", "");
            nameGCM = sharedPreferences.getString("name", "");
            recipientProfileGCM = sharedPreferences.getString("chatRecipientUrl", "");
            recipientNameGCM = sharedPreferences.getString("chatRecipientName", "");
            recipientStkidGCM = sharedPreferences.getString("recipientStkid", "");
            recipientTokenGCM = sharedPreferences.getString("recipientToken", "");
            senderTokenGCM = sharedPreferences.getString("senderToken", "");

            Log.i(TAG, " FileName GCM " + fileNameGCM + " " + " Name Rate Price &&&&& *** " + messageGCM + " "
                    + priceGCM + " " + rateGCM);
            if (firstConnect) {
                if (recipientStkidGCM.trim() == recipientStkid.trim()
                        || recipientStkidGCM.equals(recipientStkid)) {
                    MyGcmListenerService.flagSendNoti = false;
                    Log.i(TAG, " " + message);
                    // (1) get today's date
                    start = new Date();
                    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
                    timeSend = oFormat.format(start);

                    Log.i(TAG, "First connect " + firstConnect);
                    Log.i(TAG, " File Name GCMMMMMM " + fileNameGCM);
                    /*if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                    oriFName = saveFileAndImage(fileNameGCM);
                    }*/
                    /*if (fileNameGCM.contains("voice")) {
                    String durationStr;
                    MediaPlayer mPlayer = new MediaPlayer();
                    String voiceFileName = getResources().getString(R.string.url) + "/" + fileNameGCM;
                    try {
                        mPlayer.setDataSource(voiceFileName);
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                            
                    //mPlayer.start();
                    int duration = mPlayer.getDuration();
                    mPlayer.release();
                    duration = (int) Math.ceil(duration / 1024);
                            
                    if (duration < 10) {
                        durationStr = "00:0" + duration;
                    } else {
                        durationStr = "00:" + duration;
                    }
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend, fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, durationStr, null, oriFName);
                    adapter.add(stikyChat);
                    } else {*/
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend,
                            fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, nameGCM, null,
                            oriFName);
                    adapter.add(stikyChat);
                    //  }
                    Log.i(TAG, " First " + message + " " + recipientProfileGCM + " " + timeSend);
                    Log.i(TAG, "User " + txtUserName.getText().toString());

                    adapter.notifyDataSetChanged();
                    lv.setSelection(adapter.getCount() - 1);
                    new regTask2().execute("Obj ");
                } else {
                    /* if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                    saveFileAndImage(fileNameGCM);
                     }*/
                    Log.i(TAG, "..." + recipientStkidGCM.trim());
                    Log.i(TAG, "&&&" + recipientStkid.trim());
                    Log.i(TAG, "else casee");
                    //notificaton send
                    flagNotifi = true;
                    new regTask2().execute("Notification");
                }
                firstConnect = false;
            }
            lv.setSelection(adapter.getCount() - 1);
        }
    };

    /*edTxtMsg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
      Toast.makeText(getBaseContext(),
                ((EditText) v).getId() + " has focus - " + hasFocus,
                Toast.LENGTH_LONG).show();
    }
    });*/
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    edTxtMsg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutTalk.setLayoutParams(params);
            layoutTalk.setGravity(Gravity.CENTER);
            flagRecord = false;
            /*getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
            );*/
            Toast.makeText(getBaseContext(), "Touch ...", Toast.LENGTH_LONG).show();
            return false;
        }
    });
}

From source file:org.botlibre.sdk.activity.ChatActivity.java

public MediaPlayer playAudio(String audio, boolean loop, boolean cache, boolean start) {
    try {//from  w  w  w  .  jav  a2  s  .  com
        Uri audioUri = null;
        if (cache) {
            audioUri = HttpGetVideoAction.fetchVideo(this, audio);
        }
        if (audioUri == null) {
            audioUri = Uri.parse(MainActivity.connection.fetchImage(audio).toURI().toString());
        }
        final MediaPlayer audioPlayer = new MediaPlayer();
        audioPlayer.setDataSource(getApplicationContext(), audioUri);
        audioPlayer.setOnErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.wtf("Audio error", "what:" + what + " extra:" + extra);
                audioPlayer.stop();
                audioPlayer.release();
                return true;
            }
        });
        audioPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                audioPlayer.release();
                runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            beginListening();
                        } catch (Exception e) {
                            Log.e("ChatActivity", "MediaPlayer: " + e.getMessage());
                        }
                    }
                });
            }
        });
        audioPlayer.prepare();
        audioPlayer.setLooping(loop);
        if (start) {
            audioPlayer.start();
        }
        return audioPlayer;
    } catch (Exception exception) {
        Log.wtf(exception.toString(), exception);
        return null;
    }
}