9

My android app starts a service that opens a websocket to communicate to a remote server. The service spawns a thread whose run method looks like this.

public void run() {
        try {
            super.run();

            for(int i = 1; i < 1000; i++) {
                Log.d(TAG, String.format(" *** Iteration #%d.", i));
                Thread.sleep(3000); // Dummy load.
                mWebsocket.sendTextMessage("Test");
            }
        }
        catch (Exception exc) {
            Log.d(MY_TAG, "MyThread.run - Exception: " + exc.getMessage());
        }
    }

When I turn off the screen or send the app to the background, logcat shows that the loop is running, but the remote server stops receiving the test messages. Apparently, the messages are pooling somewhere because once the app is back to the foreground, the server will received a bunch of test messages. Is this the expected behavior on Android? I've tried different Websocket packages (Autobahn, okhttp3, ...) and the result is the same.

Chu Bun
  • 513
  • 1
  • 5
  • 17

1 Answers1

7

If you want this function to be guaranteed to continue to run while your app's UI is in the background, you will need to make that service run as a foreground service. There are some restrictions/guidelines on the use of foreground services, see the documentation at https://developer.android.com/guide/components/services.html.

Alternatively, if this is work that needs to occur on a periodic recurring basis and does not need to run continuously, you may be able to utilize JobScheduler; see https://developer.android.com/topic/performance/scheduling.html.

Scott Kronheim
  • 762
  • 6
  • 7
  • I just wonder why the loop is still running and output to the logcat, but the messages won't go anywhere. Is this behavior specific to websocket in genernal? to these two websocket packages? – Chu Bun Oct 17 '17 at 15:02
  • Even when the service runs in its own thread, it looks like all network activities not just websocket are stopped when main app goes to the background. I guess to use the network in this case, foreground service must be use. – Chu Bun Oct 17 '17 at 19:48
  • 1
    Yes, I really think that you will be better off with a foreground service. That will also avoid times when the Android OS will just kill your background service to reclaim resources for other apps, or to save battery. – Scott Kronheim Oct 17 '17 at 23:23