Simple
Simple

Reputation: 865

MediaPlayer duplicates song after get back to application after pressing Back Button

This is how I initialize MediaPlayer in my application:

e.g:

public class MyClass extends AppCompatActivity {
    MediaPlayer mp;

@Override
    protected void onCreate(Bundle savedInstanceState) {

      mp = MediaPlayer.create(this,R.raw.mysong);
      mp.start();
//...

When I minimize the application by pressing Back Button from my Android Device, so if I get back to the application the MediaPlayer duplicates the song and so on, the weird thing is that doesn't happen if I use Home Button instead, I can press Home Button, so the application minimizes and when I get back to the application, everything is fine, but if I do this way by pressing Back Button instead, so the problem happens.

Upvotes: 0

Views: 48

Answers (2)

Ghulam Moinul Quadir
Ghulam Moinul Quadir

Reputation: 1648

When you press Back button to minimize the application onDetroy() method of Activity is called and it destroys the Activity but your music remains created. After reopening the Activity it again calls onCreate() and your music is created again.

Now in the case of Home button onPause() and onStop() are called and your Activity does not get destroyed so if you open the app again onCreate() method does not get called and your music does not get duplicated.

You should call mp.stop() and mp.release() in onDestry() of Activty so that your music gets released before Activity destroyed.

Upvotes: 1

Roman Savin
Roman Savin

Reputation: 111

When you press back button your activity is destroyed (onDestroy() method is called) and removed from the memory by garbage collector. Since the media player is a property of the MyClass (activity) it will be removed by GC as well.

When you press home button the activity is not destroyed but stopped (onStop() method is called). The activity stays in memory that's why it works.

see Activity Lifecycle

If you want to make your media player live longer than the activity, you should create and start the media player inside a Service. Check this tutorial Using MediaPlayer in a service

Upvotes: 1

Related Questions