-1

Am just trying to play music via Media Player for n secs.

My First File:

public void Play_Music() {
    mTestUtils.ConnectDevice();
    mTestUtils.playMusic(MUSIC_PATH, STREAM_TIME);
    mTestUtils.DisconnectDevice(();
}

My Second File:

public void playMusic(String music_path, int stream_time) {

    MediaPlayer mMediaPlayer = new MediaPlayer();

    try {
        Log.i(TAG, "In Play mUsic");
        mMediaPlayer.setDataSource(music_path);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "In Handler");
                mMediaPlayer.stop();
                mMediaPlayer.release();
            }
        }, stream_time);

        Log.i(TAG, "Done Playing");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return;
}

Here my problem is how to make handler wait for given time. What is happening here is play music gets called, it executes that function and come back immediately to execute next statement in first file. I want to wait until handler function gets completed and after that i need to pass the control to first file.

Thanks in advance.

taz
  • 76
  • 8

1 Answers1

1

What I understand from your question is when you call playMusic() method, it starts playing and immediately stops your music. Because code runs top to bottom.

  1. First you are connecting device
  2. Second you are playing music
  3. Third you are disconnecting device

Happens what after second step you are calling disconnecting device immediately. I don't know what that function does. If you want to call Disconnecting function after your handler completion , then you need to use call back approach. Handler will tell that (via call back method) when to call disconnect method. I hope I answer the question.

For guidance how call back interface phenomenan work below are the helpful links.

https://stackoverflow.com/questions/3398363/how-to-define-callbacks-in-android

https://stackoverflow.com/questions/18054720/what-is-callback-in-android
Abdul Waheed
  • 4,540
  • 6
  • 35
  • 58