Android Websocket 服务持久连接 [英] Android Websocket Service Persistent Connection

查看:117
本文介绍了Android Websocket 服务持久连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 websockets 在 Android 中实现了一个聊天应用程序.但是,当用户关闭应用程序时,与服务器的 websocket 连接将丢失,并且无法接收新消息.

I implemented a chat application in Android with websockets. However when the user closes the application, the websocket connection to the server is lost and no new messages can be received.

我基本上迷路了,不知道还能去哪里,如何设置应用程序中的服务以在用户登录时以及应用程序停止后保持与服务器的连接?

I am essentially lost and do not know where else to turn, how can I setup the service in the app to stay connected to the server as the user logs in as well as after the app has been stopped?

推荐答案

我们都知道,在 Android 上连续后台执行代码是不可行的;不同的 ROM 会在没有任何保证的情况下人工处理您的后台服务(例如 START_STICKY 不会让您的服务在某些设备上重新启动),因此我们需要尽我们所能使用 可靠地执行.

As we're all aware, continuous background code execution is not feasible on Android; different ROMs will man-handle your background services without any guarantees (e.g. START_STICKY will not get your service restarted on some devices), so we need to do the best we can with the code that is reliably executed.

在这种情况下,您有一个 websocket 服务器向您的客户端提供连续信息.当您的应用程序在后台运行时,它可能会错过一些数据.当您的应用返回前台时,您的信息可能不同步,因此您需要再次与您的服务器同步,然后重新连接到您的websocket.

In this situation, you have a websocket server delivering continous information to your client. When your app is in the background, it may miss out on some data. When your app returns to the foreground, your information may be out of sync, so you need to synchronize again with your server, and then reconnect to your websocket.

在我的聊天应用程序中,我通过检查我的 websocket 服务是否在一个活动中运行 onResume 来实现这一点,该活动是我想要访问聊天数据的所有活动的超类(即不登录/注册活动).如果服务未运行,我会通过从端点提取更改然后重新启动服务来同步我的数据.这样,即使服务在后台被杀死,我仍然会在应用返回前台时获得最新数据和实时体验.

In my chat app I achieve this by checking whether my websocket service is running onResume in an activity which is a superclass of all the activities that I want to have access chatting data (i.e. not login/registration activities). If the service is not running, I synchronize my data by pulling the changes from an endpoint and then restarting the service. This way, even if the service is killed in the background I will still get the latest data and real-time experience once the app returns to the foreground.

这篇关于Android Websocket 服务持久连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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