title: How to keep android service always running?
body: <p>It always seemed some sort of black magic the way other apps keeps their services always running, but mine gets killed by the system every time.</p>
  
  <p>My app should keep a TCP socket open to the server and send/receive data when it becomes available, so it has to stay always on.</p>
  
  <p>This is what I have tried so far:</p>
  
  <p>1) Running the service in another process using this line (also with an additional line stopWithTask):</p>
  
  <pre><code>android:process="package.name.custom_process_name"
  android:stopWithTask="false"
  </code></pre>
  
  <p>2) Restarting the service when these methods get called:</p>
  
  <pre><code>onTaskRemoved()
  onDestroy()
  </code></pre>
  
  <p>3) Add <code>return START_STICKY</code> to <code>onStartCommand()</code> method</p>
  
  <p>4) Check if the service is still running when these events happen:</p>
  
  <pre><code>android.net.wifi.WIFI_STATE_CHANGED
  android.net.conn.CONNECTIVITY_CHANGE
  </code></pre>
  
  <p>- Here I am stopping the socket connection to the server if the device does not have internet connection anymore and reopening it when it gets a connection.</p>
  
  <p>Yet, my service always gets randomly killed (sometimes after few hours, sometimes after few days) by the system and doesn't restart automatically until I reopen the app.</p>
  
  <p>How does other apps, say chat apps for example, keep their services available all the time?</p>
  
  <p><strong>P.S.: Having a persistent notification would be the least of options.</strong></p>