1

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

public void playMusic(String music_path) {
    MediaPlayer mMediaPlayer = new MediaPlayer();

    try {
        mMediaPlayer.setDataSource(music_path);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mMediaPlayer.stop();
            }
        }, 20000);
        mMediaPlayer.release();
        Log.i(TAG, "Done Playing");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return;
}

My Function Caller from main file:

public void Play_Music() {
        mBtTestUtils.playMusic(MUSIC_PATH);
    }
}

Here when i do this i get the following error :

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Any help would be appreciated.

taz
  • 76
  • 8

2 Answers2

0

There are few solutions for your exception:

1) Call the Looper.prepare() before calling mBtTestUtils.playMusic(MUSIC_PATH); on caller thread.

2) If you are calling your function from different HandlerThread then you want to start your caller thread.

public void Play_Music() {
    // Starting of thread will prepare the looper (if it is handler thrad)
    callingThread.start();
    mBtTestUtils.playMusic(MUSIC_PATH);
}

3) Or while creating the Handler object, provide the main thread looper:

 new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
           // This will post your runnable on Main thread
        }
    }, 20000);
Rankush Kumar
  • 156
  • 2
  • 14
0

You need to call Looper.prepare() first. Anything that you post on a handler goes to the message queue. A Looper loops through this message queue and sends tasks for execution. Whenever you define a new Handler, it takes the Looper of the thread in which it is defined. A newly spawned thread does not contain its own Looper unless you call Looper.prepare(), hence the error. You can get a good explanation of this here.

prak253
  • 95
  • 6