title: How to handle writing to an OutputStream of BluetoothSocket in Android?
body: <p>The <a href="https://developer.android.com/guide/topics/connectivity/bluetooth#ManageAConnection" rel="nofollow noreferrer">Android developer docs</a> say that the <code>read(byte[])</code> and <code>write(byte[])</code> functions both are blocking calls so they should not be called directly from the main thread. </p>
  
  <p>I understand that <code>read()</code> only returns when there is something to be read from the socket, but do I have to spawn a new thread every time I have to write a byte to the socket's output stream using <code>write()</code> as the docs say that this function too can block if the receiving side isn't reading from the socket fast enough.</p>
  
  <p>Further, in the example of the docs, they have just called <code>write()</code> directly and even commented it saying that the function should be called directly from the activity. </p>
  
  <p>So what is the right way to handle the situation when <code>write()</code> blocks, to prevent my app from freezing and eventually throwing an ANR? Thanks!</p>