K
K
Kostya Bakay2016-04-06 00:45:24
Java
Kostya Bakay, 2016-04-06 00:45:24

How can you delay the listener's work for a certain time or until a certain condition?

The point in brief. I have an Android application that streams music from VK and has a fragment that has a SeekBar that shows the progress of the file. It works fine with local files.

private void playLocalFile() {
        mMediaPlayer = MediaPlayer.create(getActivity(), R.raw.song);
        mMediaPlayer.start();

        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {
                mTotalDuration = mp.getDuration();
                mTimelineSeekBar.setMax(mTotalDuration);
                mHandler.postDelayed(runnable, 100);
            }
        });
    }

The setOnPreparedListener listener essentially updates my SeekBar. The problem appears if the song is streamed by URL. Since streaming does not happen instantly, but with a delay of a couple of seconds, this listener of mine catches Null, since AsyncTask has not really started streaming yet and, accordingly, there is nothing in the mediaPlayer field of the AudioPlayer class (my created class for working with audio). Here is my similar method already for processing a streaming file.
private void playSong() {
            if (AppData.audioPlayer.getMediaPlayer() != null) {
                AppData.audioPlayer.getMediaPlayer().setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mTotalDuration = mp.getDuration();
                        mTimelineSeekBar.setMax(mTotalDuration);
                        mHandler.postDelayed(runnable, 100);
                    }
                });
            }
        }

The problem is that this listener is called before there is data in the audioPlayer object. How can I delay the call to the listener or do a smarter check? I tried using the sleep() method, but it didn't work.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
one pavel, 2016-04-06
@kostyabakay

developer.android.com/reference/android/media/Medi...
an example from Google should help
, how to write players
https://github.com/googlesamples/android-Universal...

Y
Yuri, 2016-10-31
@YuryBorodkin

mm, and if you use a callback? those. when ready, the function calls the passed callback parameter and your code in it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question