到目前为止,我的应用程序非常简单。只是一个播放声音的按钮。问题是,如果我按下按钮太快,我会收到错误消息并且媒体播放器不再响应。
这是我的代码。
public class Keyboard extends Activity
{
private MediaPlayer player = null;
private OnTouchListener listener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent e) {
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
System.out.println("down");
player.start();
break;
case MotionEvent.ACTION_UP:
System.out.println("up");
player.pause();
break;
}
return false;
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
player = MediaPlayer.create(getApplicationContext(),
R.raw.bloop);
player.setLooping(true);
Button foo = (Button)findViewById(R.id.A);
foo.setOnTouchListener(listener);
}
}
我所做的只是在按下按钮时调用 play(),在松开按钮时调用 pause()。这是典型日志的示例。
I/System.out( 1796): up
I/System.out( 1796): down
I/System.out( 1796): up
I/System.out( 1796): down
I/System.out( 1796): up
W/TimedEventQueue( 38): Event 2 was not found in the queue, already cancelled?
I/System.out( 1796): down
I/System.out( 1796): up
I/System.out( 1796): down
I/System.out( 1796): up
如您所见,我的调试语句在出错后仍然有效,因此 OnTouchListener 仍然有效。