I'm using the code below to read data from a bluetooth scanner. I basically
copied it off of the net, so I have some questions about the code.
1) There is a check for bytesAvailable that will usually fail,
so the code will just spin, I assume, wasting CPU and battery.
Would it be better to just use an array that is large enough
to handle any possible barcode, then lset the scanner_input_stream.read()
call block while it waits for data?
2) I'm assuming that by creating the Handler in the main thread, the
later handler.post() make the Runnable() execute in that same thread
rather than the reader thread. Is that so?
3) Why did the author take the time to copy scanner_buffer to encodedBytes?
Couldn't she have just used the original scanner_buffer to create the data
string?
Thanks!
Tobiah
The code is also here, in case the mailing list mangles it:
http://tobiah.org/code
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline
character
stop_scanner = false;
scanner_buffer_position = 0;
scanner_buffer = new byte[1024];
scanner_thread = new Thread(
new Runnable(){
public void run(){
int c = 0;
while(!Thread.currentThread().isInterrupted() &&
!stop_scanner){
c += 1;
try{
int bytesAvailable =
scanner_input_stream.available();
if(bytesAvailable > 0){
byte[] packetBytes = new
byte[bytesAvailable];
scanner_input_stream.read(packetBytes);
for(int i = 0; i <
bytesAvailable; i++){
byte b = packetBytes[i];
if(b == delimiter){
byte[]
encodedBytes = new byte[scanner_buffer_position];
System.arraycopy(scanner_buffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new
String(encodedBytes, "US-ASCII");
scanner_buffer_position = 0;
handler.post(
new
Runnable(){
public void run(){
// deal with the data.
}
}
);
} else {
scanner_buffer[scanner_buffer_position++] = b;
}
}
borg.log.write(String.format("Looking for bluetooth!! %d", c));
}
} catch (IOException ex){
stop_scanner = true;
}
}
}
});
scanner_thread.start();
}
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
---
You received this message because you are subscribed to the Google Groups "Android Developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.