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

查看:1663
本文介绍了当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软件包(高速公路,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天全站免登陆