Reputation: 35679
I'm building an application which players sound using the Media Player class.
If I use the back button to go to the menu and then reopen the app the music is still playing but if I play another track, the app seems to create a new media player. I can't put a reference saved instance state because it isn't serializble.
What's the recommended technique for keeping the reference?
Regards.
Upvotes: 0
Views: 1450
Reputation: 506
Take a look at the lifecycle diagram of Activity, and make sure you're not creating multiple MediaPlayer objects without releasing the old ones. http://developer.android.com/reference/android/app/Activity.html
Are you using MediaPlayer.create()? That allocates a new MediaPlayer object, but doesn't do anything to the old one. Call release() before calling create() a second time.
playSound(){
mp.release();
mp = MediaPlayer.create();
mp.start();
}
If you're managing it manually try putting your calls in these places.
onCreate(){
mp=new MediaPlayer();
}
onDestroy(){
mp.release();
wl.release();
}
playSound(){
mp.reset();
mp.setDatasource();
mp.prepare();
mp.start();
}
stopSound(){
mp.reset();
}
To keep the sound playing
onCreate(){
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.pzizz");
}
playSound(){
wl.acquire();
}
onDestroy(){
wl.release();
}
stopSound(){
wl.release();
}
add this to your manifest for wakelock permissions:
<uses-permission android:name="android.permission.WAKE_LOCK" />
Upvotes: 1
Reputation: 10479
I would recommend you place your MediaPlayer behind a Service. I've found that a really good example of how to do this, as well as bind to that service and play media, is the NPR Radio app which is open source. You can find the source here
Upvotes: 2