我正在尝试处理媒体播放器错误,当错误发生时,我想要播放一条消息,然后播放下一首歌曲,但无论何时发生错误,它都会崩溃。
这是我正在尝试的代码
public class player1 extends ActionBarActivity implements View.OnClickListener,OnErrorListener{
MediaPlayer mp;
ArrayList<File> mySongs;
int position;
Uri u;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songlist");
position = b.getInt("pos", 0);
u = Uri.parse(Uri.encode(mySongs.get(position).toString()));
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
String errorWhat;
switch(what){
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
errorWhat = "MEDIA_ERROR_UNKNOWN";
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
errorWhat = "MEDIA_ERROR_SERVER_DIED";
break;
default:
errorWhat = "!";
}
String errorExtra;
switch(extra){
case MediaPlayer.MEDIA_ERROR_IO:
errorExtra = "MEDIA_ERROR_IO";
break;
case MediaPlayer.MEDIA_ERROR_MALFORMED:
errorExtra = "MEDIA_ERROR_MALFORMED";
break;
case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
errorExtra = "MEDIA_ERROR_UNSUPPORTED";
break;
case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
errorExtra = "MEDIA_ERROR_TIMED_OUT";
break;
default:
errorExtra = "!";
}
Toast.makeText(player1.this,
"Error" + "\n"
+ errorWhat + "\n"
+ errorExtra,
Toast.LENGTH_LONG).show();
//release
mp.stop();
mp.release();
initMediaPlayer();
return true;
};
private void initMediaPlayer() {
Toast.makeText(player1.this,
"playomng next song",
Toast.LENGTH_LONG).show();
position = (position + 1)%mySongs.size();
u = Uri.parse(Uri.encode(mySongs.get(position).toString()));
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
}
}
如何在不强制媒体播放器关闭的情况下设法处理这些错误?
答案 0 :(得分:0)
不仅仅是在你的代码上添加一个乐队助手,而是找到实际问题的位置可能更明智。如果你能找到你收到错误的行,你可以简单地将代码包装在
中try{
//code that crashes here
}
catch(Exception e){
Toast.makeText(context, "Media error", LENGTH_SHORT).show();
}
编辑: 请注意,通过try / catch简单地防止崩溃可能会导致错误。如果您可以发布您的logcat,我们可能能够找出您的实际错误。
答案 1 :(得分:0)
mp.setOnErrorListener(this);
。i.getExtras();
它可能为null,因此调用b.getParcelableArrayList("songlist");
可能会使您的应用程序崩溃。