title: Android background thread continually listening to an UDP port
body: <p>I really appreciate that you take a couple of minutes to read my problem, thanks in advance!  </p>
  
  <p>I am building a non-public app for some specific users and here is my problem:</p>
  
  <hr>
  
  <p>I have a service for background workloads in which I started a user thread that continually listens to an UDP port. It works fine when the device screen is turned on but lost all UDP packets when screen turned off.  </p>
  
  <p>Following is what I wrote in the thread:</p>
  
  <pre><code>// Android os v7.1.2, wifi 
  DatagramSocket s;
  DatagramPacket p;  // already initialized 
  while (true) {
      try {
          if (s == null || !s.isBound()) {
              s = new DatagramSocket(60000);
              s.setSoTimeout(0);
          } else {
              s.receive(p);  
              ... 
          }
      } catch(Exception e) {
          ...
      }
  }
  </code></pre>
  
  <p>I guess it's a power-management-related problem on Android devices. I have tried place <strong>PowerManager.WakeLock.aquire()</strong> and <strong>release()</strong> before and after the while loop but that does take effect.  </p>
  
  <p>To be clear, this app is built for specific clients and does not care about how much battery it will drain(probably the only running app on device in most times lol).   </p>
  
  <p>Any idea what should I do? Should I choose <strong>IntentService</strong> or something like that to achieve this "infinite" UPD port listening work? I have spent a whole weekend seeking solutions in Android docs, but non of the examples said I could do a instantaneously triggered UDP socket listening[sad face]. </p>
  
  <p>For more information, I logged all three socket connection threads started in my service and find out that the one thread which uses tcp socket to send sth to server and wait for sth sent back works quite fine... </p>