当Android应用程序进入后台时,Websocket暂停 [英] Websocket paused when android app goes to background

查看:88
本文介绍了当Android应用程序进入后台时,Websocket暂停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 android 应用程序启动了一个服务,该服务打开一个 websocket 以与远程服务器进行通信.该服务生成一个线程,其运行方法如下所示.

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());
        }
    }

当我关闭屏幕或将应用程序发送到后台时,logcat 显示循环正在运行,但远程服务器停止接收测试消息.显然,消息在某处汇集,因为一旦应用程序回到前台,服务器将收到一堆测试消息.这是 Android 上的预期行为吗?我尝试了不同的 Websocket 包(Autobahn、okhttp3、...),结果是一样的.

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.

推荐答案

如果您希望在您的应用程序的 UI 在后台运行时保证此功能继续运行,您需要将该服务作为前台服务运行.前台服务的使用有一些限制/指南,请参阅https://的文档developer.android.com/guide/components/services.html.

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.

或者,如果这是需要定期重复发生并且不需要连续运行的工作,您可以使用 JobScheduler;参见 https://developer.android.com/topic/performance/scheduling.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.

这篇关于当Android应用程序进入后台时,Websocket暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆