Shu*_*ubh 8 java android android-mediaplayer
这是我的代码
if (player != null) {
if(player.isPlaying()){
player.pause();
player.stop();
}
player.release();
}
Run Code Online (Sandbox Code Playgroud)
这是错误
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)
Run Code Online (Sandbox Code Playgroud)
我是Android的初学者,我对a的生命周期非常困惑MediaPlayer.
这是从onBackPressed()另一个函数调用的适配器中的函数Activity.player是一个类变量.
我MediaPlayer在同一个文件中发布这个
public void onClick(View v) {
try {
if (player != null) {
player.stop();
player.release();
}
} catch (Exception e) {
}
player = MediaPlayer.create(activityContext, soundId);
player.start();
}
Run Code Online (Sandbox Code Playgroud)
ear*_*jim 10
问题是您没有跟踪MediaPlayer实例的状态.
在呼叫之前,isPlaying()您只执行null值检查,但player仍然可以释放(但不能null).
调用isPlaying()已发布的MediaPlayer实例将导致IllegalStateException.
为避免这种情况,您可以将其设置player为null释放时:
player.release();
player = null;
Run Code Online (Sandbox Code Playgroud)
或者您可以使用boolean标志来跟踪其状态:
boolean isReleased;
// ...
player.release();
isReleased = true;
Run Code Online (Sandbox Code Playgroud)
所以你可以在必要时检查这个标志:
if (player != null && !isReleased) {
if(player.isPlaying()) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
(不要忘记false在适当的时候设置它)
| 归档时间: |
|
| 查看次数: |
1329 次 |
| 最近记录: |