title: Android - synchronizing threads with onSensorChanged to send udp Packets
body: <p>I am trying to make a multiplayer game on android in which players use the accelerometer to move an object around. Initially I had used TCP to send packets which contain the X &amp; Y coordinates of the player as a JSON string, inside the onSensorChanged() attached to the accelerometer(with SENSOR_DELAY_GAME). But due to latency issues, I decided to try out UDP.</p>
  
  <p>Now earlier, I created a seperate thread which created a new socket and I used the following code:</p>
  
  <pre><code>public void onSensorChanged(SensorEvent event) {
  // Other Stuff
      PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
                      out.println(coords.toString());
  }
  </code></pre>
  
  <p>And I had:</p>
  
  <pre><code>socket = new Socket(serverAddr, Port);
  </code></pre>
  
  <p>in another thread.</p>
  
  <p>Since UDP does not provide any such methods to send the data from the main thread due to <code>NetworkOnMainThreadException</code><strong>,</strong> I figured I have to do the packet transmission in another thread. But the problem is that I'm calculating the data to be sent inside the <code>onSensorChanged()</code>, and I want to send a packet each time the <code>onSensorChanged()</code> is invoked.</p>
  
  <p>I'm relatively new to Java and multithreading and tried reading about synchronization, but cannot seem to properly understand and implement it here. So I'd greatly appreciate if someone can point out an approach to solve this.
  I'd also like to know if sending the coordinates at each <em>SensorChange</em> is a good idea and whether there is a way to optimize the data so that I can still use TCP without latency issues. And I was also wondering if there was any possible way to make <code>onSensorChanged()</code> run as a separate thread...?</p>