Websocket paused when android app goes to background
Asked Answered
P

1

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.

Parthenia answered 16/10, 2017 at 23:50 Comment(0)
Z
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.

Zug answered 17/10, 2017 at 0:11 Comment(3)
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?Parthenia
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.Parthenia
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.Zug

© 2022 - 2024 — McMap. All rights reserved.