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

时间:2018-05-14 17:32:46

标签: android

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.

2 个答案:

答案 0 :(得分:1)

当您按下后退按钮时,您的活动被销毁(调用onDestroy()方法)并被垃圾收集器从内存中删除。由于媒体播放器是MyClass(活动)的属性,因此它也将被GC删除。

按home键时,活动不会被销毁但会停止(调用onStop()方法)。活动保留在内存中,这就是它工作的原因。

请参阅Activity Lifecycle

如果您想让您的媒体播放器比活动更长寿,您应该在服务中创建并启动媒体播放器。 查看本教程Using MediaPlayer in a service

答案 1 :(得分:1)

当您按“返回”按钮以最小化调用onDetroy()的{​​{1}}方法时,它会销毁该活动,但您的音乐仍会创建。重新打开Activity后,再次拨打Activity,您的音乐会再次创建。

现在,如果主页按钮onCreate()onPause()被调用且您的onStop()未被销毁,那么如果您再次打开应用Activity方法无法获取被叫,你的音乐不会重复。

您应该在onCreate()的{​​{1}}内拨打mp.stop()mp.release(),以便在onDestry()销毁之前释放您的音乐。