Hardware Reference
In-Depth Information
The ability to send data is already complete and handled by the
write
function. The ability to receive data is not as
straightforward. Because the code is event driven and normally responds to user interaction, a type of continuous loop
needs to be created that does not interfere with the rest of the program. This is accomplished by implementing a thread
that will listen to the incoming file stream for new data and call a function so that the data can be worked with.
To implement a thread, we need to create and start a
Runnable
class, so add
implements Runnable
to the end of the
activity declaration just before the starting curly brace and after
extends Activity
making the class declaration read as.
public class CH4ExamplesActivity extends Activity implements Runnable {
The thread needs to be created and started. This is done in the
openAccessory
function located in part 5
Listing 4-6. The two lines of code in Listing 4-7 are placed between the following existing lines:
SendtoADK = new FileOutputStream(fd);
Log.d(TAG, "accessory opened");
The new lines of code will start a function named
run
in the current class every time the
openAccessory
function
is executed.
Listing 4-7.
New Lines for the openAccessory Function
Thread ADKreadthread = new Thread(null, this, "ADK_Read_Thread");
ADKreadthread.start();
The
run
function needs to be defined within the class and can be added below the
write
function of part 6
Listing 4-6. The functions must be named
run
because of the abstraction from the runnable class. The new function
is as described in Listing 4-8. The function normally would execute once and end as a separate thread from the
original program. In this case, it needs to run in a continuous loop, so we create a
while (true)
loop. Under normal
circumstances, once a loop of this nature is encountered, the rest of the program cannot continue to function until
the loop is finished. However, this loop is in a separate place and acts as a different program from the main program,
and allows for the rest of the code to execute as normal. This function constantly monitors the
ReceiveFromADK
data
stream for new information, places the data in a new data class, and informs a function that there is new data ready to
be handled by the main program.
Listing 4-8.
New Function to Constantly Check for New Incoming Data
public void run() {
int RevivedBytes = 0;
while (true) { // run constantly
byte[] buffer = new byte[80]; // max size capable is 16384 but slows the program down
try {
RevivedBytes = ReciveFromADK.read(buffer);
}
catch (IOException e) {
Log.e(TAG, "Read failed", e);
break;
}
if (RevivedBytes >= 1 ) {
Message MakeBufferTransferable = Message.obtain(IncomingDataHandler);
MakeBufferTransferable.obj = new BufferData( buffer ,RevivedBytes);
IncomingDataHandler.sendMessage(MakeBufferTransferable);
}
}// end while
}// end public void run()