User manual

AOAA Kit – Software User’s Guide
Page 36
Copyright 2012 © Embedded Artists AB
if (len >= 2) {
Message m = Message.obtain(handler,
AccessoryControl.MESSAGE_IN_BTN_1);
m.arg1 = toInt((byte)0, buffer[pos + 1]);
handler.sendMessage(m);
}
pos += 2;
break;
…
The Handler which receives the message must also be modified to react on the message, which
typically is to update something in the user interface. Open the MainActivity.java file and locate the
instantiation of the Handler and add handling of the new message.
private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case AccessoryControl.MESSAGE_IN_TRIMPOT:
trimPotArea.setText("" + msg.arg1);
break;
case AccessoryControl.MESSAGE_IN_BTN_1:
btn1Area.setText("" + msg.arg1);
break;
case AccessoryControl.MESSAGE_IN_BTN_2:
btn2Area.setText("" + msg.arg1);
break;
…
Note: The reason for using a Handler is that the Android UI toolkit is not thread-safe which means that
the UI must only be manipulated from the UI thread. Read more about this in “Painless Threading”,
reference [15], and “Android Developers – Threading and Processes”, reference [16].
6.1.3 Send a New Message from the Android App
If the Android App should send a new message to the accessory it is the
AccessoryControl.writeCommand method that must be used. In the demo, messages are sent as a
reaction to the user pressing a button in the user interface. The onClick method is invoked when a user
presses a button and as the example below illustrates the writeCommand method is called.
public void onClick(View v) {
switch (v.getId()) {
case R.id.redBtn:
accessoryControl.writeCommand(
AccessoryControl.MESSAGE_OUT_RGB_6_LED,
AccessoryControl.MESSAGE_RGB_VAL_RED,
(((ToggleButton)v).isChecked() ? 1 : 0));
break;
case R.id.greenBtn:
accessoryControl.writeCommand(
AccessoryControl.MESSAGE_OUT_RGB_6_LED,
AccessoryControl.MESSAGE_RGB_VAL_GREEN,
(((ToggleButton)v).isChecked() ? 1 : 0));
break;