java – Is the MediaPlayer.create() method called in the background?

Question:

I was reading the Android Media Playback documentation and I had a question. In the documentation it said that it is not advisable to call the mediaPlayer.prepare() method in the thread responsible for the UI, and I would like to know if the MediaPlayer.create(this, R.raw.amostra_de_audio) is called in the background or if some additional configuration is needed . Thank you very much in advance.

Answer:

The MediaPlayer.create() method is not asynchronous. It couldn't be because it returns an instance of MediaPlayer .
It internally calls the prepare() method thus returning the MediaPlayer ready to be used.

To achieve the same asynchronously you will have to create an instance, through new and call the prepareAsync() method.

MediaPlayer myMediaPlayer = new MediaPlayer();
....
....
myMediaPlayer.setDataSource(url);
myMediaPlayer.prepareAsync();

myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

    @Override
    public void onPrepared(MediaPlayer player) {
        player.start();
    }

});

The onPrepared() method of the OnPreparedListener passed to the setOnPreparedListener() method will be called when the MediaPlayer is ready to be used.

Scroll to Top