J. Doe
J. Doe

Reputation: 325

How to avoid creating a new instance of MediaPlayer when returning to activity

I'm using the MediaPlayer and it keeps playing in the background when the user leaves the activity by pressing back (I want this to happen), however when the user returns, they have no control over the already playing MediaPlayer since the line mediaPlayer = new MediaPlayer() instantiates a new one.

I also cannot get mediaPlayer.create() to work since I am using a connection to soundcloud requiring the

mediaPlayer1.reset();
mediaPlayer1.setDataSource(getResources().getString(R.string.Basic_lesson_1));
mediaPlayer1.prepareAsync();

lines. How can I instantiate a new MediaPlayer only if one does not already exist?

Upvotes: 2

Views: 429

Answers (3)

Shiva Acharjee
Shiva Acharjee

Reputation: 193

How about evoking the method stop() on backKeyPress

Upvotes: 0

Sohail Zahid
Sohail Zahid

Reputation: 8149

Create Global static media Player and always perform validation as @Pravin says while create media player like.

if(mediaPlayer == null){
  mediaPlayer = new MediaPlayer()
 }  

Upvotes: 1

David
David

Reputation: 16277

private static MediaPlayer mediaPlayer1 = null;

//SomeActivity's onCreate()
if(mediaPlayer1 == null)
    mediaPlayer1.create(...);

Upvotes: 0

Related Questions