使用 Wii Remote 时,我的 Java 代码有问题。我的情况是“当按钮 A 按下时,在屏幕上打印一些东西(在我的情况下是原始加速度)直到释放按钮 A”,所以,经过几天的搜索,我使用 TimerTask 和 Timer 来完成任务。它打印了原始加速度。但是,在我松开按钮 A 后,它无法停止打印。这是我的代码:
public class TestTimerTask implements WiimoteListener {
public RawAcceleration rawacc;
public static void main(String[] args){
Wiimote[] wiimotes = WiiUseApiManager.getWiimotes(1, true);
Wiimote wiimote = wiimotes[0];
wiimote.activateMotionSensing();
wiimote.toString();
wiimote.addWiiMoteEventListeners(new TestTimerTask ());
}
@Override
public void onButtonsEvent(WiimoteButtonsEvent wbe) {
boolean check = false;
Timer timer = new Timer();
TaskNeedToDo task = new TaskNeedToDo();
if(wbe.isButtonAJustReleased()){
System.out.println("Button A Just Released");
task.setCheck(false);
task.cancel();
timer.cancel();
}
if(wbe.isButtonAJustPressed()){
// check = false;
try {
System.out.println("Button A Just Pressed");
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:sss");
Date temp = new Date (System.currentTimeMillis());
Date now = dateFormatter.parse(dateFormatter.format(temp));
int period = 300;
task.setCheck(true);
task.setRawAcc(rawacc);
timer.schedule(task, 0, period);
} catch (ParseException ex) {
System.out.println("Error when take current time");
}
}
if(wbe.isButtonBHeld())
WiiUseApiManager.shutdown();
}
@Override
public void onIrEvent(IREvent ire) {
System.out.println("onIrEvent oocur");
}
@Override
public void onMotionSensingEvent(MotionSensingEvent mse) {
rawacc = mse.getRawAcceleration();
}
class TaskNeedToDo extends TimerTask {
private boolean check;
private RawAcceleration value;
public boolean getCheck(){
return check;
}
public void setCheck(boolean check){
this.check = check;
if(check == false)
this.cancel();
}
public RawAcceleration getRawAcc(){
return value;
}
public void setRawAcc(RawAcceleration value){
this.value = value;
}
@Override
public void run() {
if(check == false)
this.cancel();
System.out.println(value);
System.out.println(check);
}
}
结果如下:
Button A Just Pressed
Raw acceleration : (14, 115,148)
true
Raw acceleration : (14, 115,148)
true
Raw acceleration : (14, 115,148)
true
Button A Just Released
Raw acceleration : (14, 115,148)
true
Raw acceleration : (14, 115,148)
true
Raw acceleration : (14, 115,148)
true
Raw acceleration : (14, 115,148)
true
Raw acceleration : (14, 115,148
true
检查仍然是真的,所以它不能停止:(谢谢你帮助我:D