简体   繁体   English

当我在后退按钮上添加onpause方法时,铃声应用不会逻辑崩溃

[英]Not logic crash of ringtone app when I add onpause method on back button

I have app that uses media player for sounds. 我有使用媒体播放器播放声音的应用程序。 Code that I use to stop sounds when I press back button is: 我按下“后退”按钮时用来停止声音的代码是:

@Override
public void onBackPressed() {
    super.onBackPressed();
    if (mp != null) {
        mp.reset();
        mp.release();
    }
   finish();
}

This code is working good, but if app suddenly gets interrupted, and sound is still playing it needs to stop, so I added the same thing in onPause method (same case if I add onStop method). 该代码运行良好,但是如果应用突然中断,并且声音仍在播放,则需要停止,因此我在onPause方法中添加了相同的内容(如果添加onStop方法,则是相同情况)。

  @Override
protected void onPause() {
    super.onPause();
    if (mp != null) {
        mp.reset();
        mp.release();
    }
}

Now, when I press back, app crashes instead of going back (that worked before I added onPause method) onPause is working good, as sounds stops if I press Home button I'm getting this errors in logcat: 现在,当我按回去时,应用程序崩溃而不是回退(在我添加onPause方法之前可以运行)onPause正常运行,因为如果按Home按钮,声音会停止,我在logcat中得到以下错误:

java.lang.RuntimeException: Unable to pause activity
java.lang.IllegalStateException

... ...

You can't reset MediaPlayer, that is released. 您无法重置已发布的MediaPlayer。 Because after release the resource, that was used for playing sound is not available. 因为释放资源后,用于播放声音的资源不可用。 You should change: 您应该更改:

mp.reset();
mp.release();

to: 至:

mp.release();
mp = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM