10

我有一个AlertDialog,当我单击它时它会停止播放声音,但在某些设备上似乎调用onStop()会抛出一个IllegalStateException,但是为什么呢?

如果对话框打开,则表示声音正在播放,因此应该是音频未播放的情况。

我现在用 try catch 包围了它,但这是什么原因造成的呢?

alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                try{
                mp.stop(); //error
                mp.reset();
                mp.release();
                }catch(Exception e){
                    Log.d("Nitif Activity", e.toString());
                }
                v.cancel();

                popupMessage();                 
                finish();
            }
        });
4

4 回答 4

29

检查mp != null可以防止NullPointerExceptionIllegalStateException不能由此引起。

The reason you get that error is that the player is in a state where it can't stop(). If you have a look at the state-diagram at the top of the MediaPlayer documentation you can see that stop can only be called after the player is in the Prepared state. The next possibility is that you have already called release() or reset() which will also result in that error.

You can call stop() only in Prepared, Started, Paused, PlaybackComplete or Stopped state. All other states produce that error.

So you either do prepareAsync() and the user hits the button before your player is prepared or you have code that releases or resets the player before you hit the button.

于 2012-05-04T18:35:09.873 回答
3

我猜您可能在执行这些行之前将您的实例清空。当我收到此错误时,我首先检查 null。

if (mp != null) {
    try {
        mp.stop(); //error
        mp.reset();
        mp.release();
    } catch(Exception e){
        Log.d("Nitif Activity", e.toString());
    }
}
于 2012-05-04T17:53:38.200 回答
0

显然mp没有初始化,开发资源

尝试添加:

if(mp != null)
于 2012-05-04T17:52:02.673 回答
0

检查 mp!=null 可以防止它何时为空,但您的媒体播放器永远不会为空。只需添加 mp=null; 你在哪里做 mp.stop();

于 2017-08-23T10:07:03.953 回答