我完成了这个项目:sample-button
但是我需要将其更改为在按下按钮时保持 LED 亮着,并在再次按下按钮后将其熄灭。
我该怎么做?
我完成了这个项目:sample-button
但是我需要将其更改为在按下按钮时保持 LED 亮着,并在再次按下按钮后将其熄灭。
我该怎么做?
删除onKeyDown
覆盖方法中的代码并更改setLedValue
为:
private void setLedValue(boolean value) {
try {
mLedGpio.setValue(!mLedGpio.getValue());
} catch (IOException e) {
Log.e(TAG, "Error updating GPIO value", e);
}
}
(您最好删除 onKeyDown 而不是 onKeyUp 以获得更好的用户体验。从用户体验的角度来看,在释放键时更改某些内容比在第一次按下时执行操作要好得多。)
如果你想看到整个班级发生了变化,它看起来像这样:
public class ButtonActivity extends Activity {
private Gpio mLedGpio;
private ButtonInputDriver mButtonInputDriver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PeripheralManager pioService = new PeripheralManager.getInstance();
try {
mLedGpio = pioService.openGpio(BoardDefaults.getGPIOForLED());
mLedGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mButtonInputDriver = new ButtonInputDriver(
BoardDefaults.getGPIOForButton(),
Button.LogicState.PRESSED_WHEN_LOW,
KeyEvent.KEYCODE_SPACE);
mButtonInputDriver.register();
} catch (IOException e) {
throw new IllegalStateException("Error configuring GPIO pins", e);
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SPACE) {
toggleLedValue();
return true;
}
return super.onKeyUp(keyCode, event);
}
/**
* Update the value of the LED output.
*/
private void toggleLedValue() {
try {
mLedGpio.setValue(!mLedGpio.getValue());
} catch (IOException e) {
Log.e(TAG, "Error updating GPIO value", e);
}
}
@Override
protected void onDestroy(){
super.onDestroy();
mButtonInputDriver.unregister();
try {
mButtonInputDriver.close();
} catch (IOException e) {
Log.e(TAG, "Error closing Button driver", e);
}
try {
mLedGpio.close();
} catch (IOException e) {
Log.e(TAG, "Error closing LED GPIO", e);
}
}
}
尝试在ButtonActivity.java中替换以下回调方法
static boolean mToggle ;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SPACE) {
// Turn on the LED
mToggle = !mToggle;
setLedValue(mToggle);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SPACE) {
// Turn off the LED
// setLedValue(false);
return true;
}
return super.onKeyUp(keyCode, event);
}