Websocket paused when android app goes to backgrou

2020-02-02 00:46发布

问题:

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.

回答1:

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.