Reputation: 1398
I use Gingerbread. I already talk to a native serial port (RS-232 native UART, not USB dungle). This is done through java.io and a small piece of native code written in C to open and close the stream and configure the baudrate. It works but my first thought was that it is not efficient because I need to setup a thread that constantly poll the inputstream to check if there are bytes coming from the serial port. What a wasteful way to use CPU and batteries.
private InputStream mInputStream;
private ReadThread mReadThread;
private class ReadThread extends Thread {
@Override
public void run() {
super.run();
while(!isInterrupted()) {
int size;
try {
byte[] buffer = new byte[64];
if (mInputStream == null) return;
size = mInputStream.read(buffer);
if (size > 0) {
onDataReceived(buffer, size);
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
What I Thought I needed to do is to have the same kind of signal as for other events in android where I can setup some kind of listener that would allow me to be informed of some bytes coming and wake up my thread that will take care of the incoming data. I did not find anything like that in the APIs.
But, after looking and researching more, finally, I think this is not wasteful but I'd like an opinion from someone who knows about how threads work in Android. Let's look at codes lines.
size = mInputStream.read(buffer);
is actually a blocking read. I looked how the device was opened and it is done in C through a NDK/JNI interface and it is open without the flag "NOBLOCK/NODELAY". Therefor, it should not spin constantly in the while loop but just get blocked on the mInputStream.read and the Kernel should just switch to another thread until there is some data available to read. In such case, this code would be totally fine. Is this assumption true?
I'd like to know that because my embedded system main purpose is to display videos most of the time and I don't want what I manage behind the scene to suck-up to much resources and give some hiccups in the video playback.
Upvotes: 2
Views: 3480
Reputation: 1398
After writing the application, and testing, I can say that the last assumption made in the question is actually true. If the device is open without the flag "NOBLOCK/NODELAY", the thread will be suspended on the mInputStream.read() until there is data available. No wasteful polling.
Upvotes: 2
Reputation: 4725
You can use selector() from java.nio packages.
http://developer.android.com/reference/java/nio/channels/Selector.html
Also refer http://www.drdobbs.com/jvm/high-performance-io-with-java-nio/184406242
Upvotes: 0