I have a toggle button that I press, keyboard keys are then pressed at half second delays. To stop a user pressing the button twice in quick succession and messing this up I disable the button while the commands are running, and enable it again after. This is a lot of messing about on the UI thread with repeated code. What would be a better way of doing this? Queue up all the commands in a thread or something and leave the user being able to press the button as much as they want? Or jsut abstract this runonui functionality to it's own method. Something else?
public void pushtotalk(final View view) {
final boolean on = ((ToggleButton) view).isChecked();
new Thread(new Runnable() {
@Override
public void run() {
try {
Instrumentation inst = new Instrumentation();
if (on)
{
runOnUiThread(new Runnable() {
public void run() {
((ToggleButton) view).setEnabled(false);
}
});
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_NUMPAD_MULTIPLY);
Thread.sleep(500);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_9);
Thread.sleep(500);
runOnUiThread(new Runnable() {
public void run() {
((ToggleButton) view).setEnabled(true);
}
});
}
else
{
runOnUiThread(new Runnable() {
public void run() {
((ToggleButton) view).setEnabled(false);
}
});
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_POUND);
Thread.sleep(500);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_9);
Thread.sleep(500);
runOnUiThread(new Runnable() {
public void run() {
((ToggleButton) view).setEnabled(true);
}
});
}
}
catch(InterruptedException e){
Log.d(TAG, "Failed to send keycodes: " + e.getMessage());
}
}
}).start();
}