MediaPlayer中的IllegalStateException [英] IllegalStateException in MediaPlayer
问题描述
这是我的代码
if (player != null) {
if(player.isPlaying()){
player.pause();
player.stop();
}
player.release();
}
这是错误
FATAL EXCEPTION: main
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.mindefy.sindhipathshala.RecViewAdapter.mediafileRelease(RecViewAdapter.java:234)
at com.mindefy.sindhipathshala.SectionFruits.onBackPressed(SectionFruits.java:252)
我是Android的初学者,我对MediaPlayer
的生命周期感到非常困惑.
I am a beginner in Android and i am very confused with the lifecycle of a MediaPlayer
.
这是从另一个Activity
的onBackPressed()
函数调用的适配器中的函数. player
是一个类变量.
This is a function in an adapter that is called from onBackPressed()
function of another Activity
. player
is a class variable.
我将这个MediaPlayer
发布到与
public void onClick(View v) {
try {
if (player != null) {
player.stop();
player.release();
}
} catch (Exception e) {
}
player = MediaPlayer.create(activityContext, soundId);
player.start();
}
推荐答案
问题是您无法跟踪MediaPlayer
实例的状态.
The problem is you don't keep track of the state of your MediaPlayer
instance.
在调用isPlaying()
之前,您只能执行null
值检查,尽管player
仍可以释放(但不能释放null
).
Before calling isPlaying()
you only perform a null
value check, although player
can still be released (but not null
).
在已发布的MediaPlayer
实例上调用isPlaying()
将导致IllegalStateException
.
Calling isPlaying()
on a released MediaPlayer
instance will result in an IllegalStateException
.
为避免这种情况,例如,可以在释放它时将player
设置为null
:
To avoid this, you could for example set player
to null
when you release it:
player.release();
player = null;
或者您可以使用boolean
标志来跟踪其状态:
Or you could use a boolean
flag to keep track of its state:
boolean isReleased;
// ...
player.release();
isReleased = true;
因此您可以在必要时检查此标志:
So you could check for this flag when necessary:
if (player != null && !isReleased) {
if(player.isPlaying()) {
// ...
}
}
(不要忘记在适当的时候将其设置为false
)
(don't forget to set it to false
when appropriate)
这篇关于MediaPlayer中的IllegalStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!