我写了一个响应列表视图项目点击的代码。我打算列表中单击的项目将通过Toast
消息返回媒体源的URI,然后开始播放。
这是代码。
lvAlarmTones.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
ringtone = ringtoneSources.get(position);
Uri toneUri = Uri.parse(ringtone);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(ChooseAlarmToneActivity.this, toneUri);
mediaPlayer.start();
Log.i(ApplicationManager.LOG, "Media loaded: " + ringtone);
} catch (IOException e) {
Toast.makeText(ChooseAlarmToneActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(ChooseAlarmToneActivity.this, ringtone, Toast.LENGTH_SHORT).show();
}
});
当我运行此代码时,我设法成功获取带有URI的Toast
,但我仍然无法播放媒体。
答案 0 :(得分:0)
这意味着您的点击监听器没有任何问题,但媒体播放器代码执行出错了。
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(ChooseAlarmToneActivity.this, toneUri);
mediaPlayer.start();
Log.i(ApplicationManager.LOG, "Media loaded: " + ringtone);
} catch (IOException e) {
Toast.makeText(ChooseAlarmToneActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
检查您的捕获异常会发现错误,我强烈建议您处理错误使用OnErrorListener
答案 1 :(得分:0)
我通过修改代码解决了这个问题。
lvAlarmTones.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
ringtone = ringtoneSources.get(position);
Uri toneUri = Uri.parse(ringtone);
if(mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer = MediaPlayer.create(ChooseAlarmToneActivity.this, toneUri);
mediaPlayer.start();
Toast.makeText(ChooseAlarmToneActivity.this, ringtone, Toast.LENGTH_SHORT).show();
}
});