title: Android/Smack: Keep XMPP connection alive in sleep mode
body: <p>I have an Android application that has a chat client as one of its features. The chat client uses XMPP based on the <a href="https://www.igniterealtime.org/projects/smack/index.jsp" rel="noreferrer">Smack</a> library for Android and running <a href="https://www.igniterealtime.org/projects/openfire/" rel="noreferrer">Openfire</a> as XMPP server in the background. The connection is established using <a href="https://en.wikipedia.org/wiki/BOSH" rel="noreferrer">BOSH</a> The whole XMPP connection handling is implemented as a service to run and listen in the background for incoming messages even if not activity of the app is in the foreground. So far, everything works perfectly fine.</p>
  
  <p>The only problem seems to be the sleep mode. In the emulator (when set to "Stay Awake") or with the phone in use, the XMPP connections is holding and the app can send and receive messages. However, once the phone goes into sleep mode, the XMPP connection breaks down -- I can see it in the Admin Console of the Openfire server that the user is offline. Intuitively, I want to receive messages all the time like, e.g., WhatsApp.</p>
  
  <p>Of course, I've searched online including Stackoverflow, but I couldn't get a definitive answer. Often the use case seems to be that a task has to be performed periodically, say, once every hour. But this doesn't seem to fir in case of a chat client. Since I assume this is a common use case -- after all, there a so many chat apps or apps with chat features out there -- these are my question:</p>
  
  <ul>
  <li><p>How to I have to change / extend the app that I can receive chat message while the phone is sleeping?</p></li>
  <li><p>I've stumbled upon <code>WakeLock</code>. Is this the way to go or are these not suitable for my use case?</p></li>
  <li><p>Since Lollipop, there's also the <code>JobScheduler</code> API which itself uses <code>WakeLock</code>. Any better?</p></li>
  <li><p>How does, for example, WhatsApp handles this case?</p></li>
  </ul>
  
  <p>On a side note: I have problems with the sleep mode using the emulator for debugging. When I switch off "Stay Awake" in the emulator, the screen goes black after 1+ min and the XMPP connection breaks. But I somehow have no idea how to wake up / switch the emulator back on once it went black. Android Studio actually tells me at some point that the device or something is gone, and I have to restart the emulator again.</p>