title: Access serial port (/dev/tty*) incoming data without polling
body: <p>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.</p>
  
  <pre><code>    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 &gt; 0) {
                      onDataReceived(buffer, size);
                  }
              } catch (IOException e) {
                  e.printStackTrace();
                  return;
              }
          }
      }
  }
  </code></pre>
  
  <p>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. </p>
  
  <p>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. </p>
  
  <pre><code>size = mInputStream.read(buffer);
  </code></pre>
  
  <p>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?</p>
  
  <p>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.   </p>