Android中如何处理涉及socket的活动生命周期?

发布于 2024-09-03 08:30:20 字数 550 浏览 2 评论 0原文

  • 我有一个 Android 活动,它又启动一个线程。
  • 在线程中,我打开一个持久的 TCP 套接字连接。
  • 当套接字连接到服务器时,动态数据被下载。
  • 当接收到数据时,线程使用处理程序类向活动发送消息。

现在,如果用户碰巧从纵向模式切换到横向模式,则 Activity 会收到 onDestroy 调用。此时我关闭套接字并停止线程。

当 Android 切换横向模式时,它会再次调用 onCreate,我必须重新连接套接字。此外,活动接收到的所有数据都需要再次下载,因为服务器无法知道之前发送了什么,即没有“恢复”功能。

因此,问题在于,当横向模式改变时,会一直重新发送大量数据。

我在这里有什么选择?

  • 我是否应该创建一个处理向服务器发送的套接字流量的服务,这样我总是可以获得服务器在服务中发送的所有数据。
  • 或者我应该一起禁用横向模式吗?
  • 或者我最好的选择是重写我的服务器,这是一项非常大的工作:-)

欢迎所有输入:-)

/ Henrik

  • I have an Android activity which in turn starts a thread.
  • In the thread I open a persistent TCP socket connection.
  • When the socket connects to the server dynamic data is downloaded.
  • The thread sends messages using Handler-class to the activity when data has been received.

Now if the user happens to switch from portrait to landscape mode the activity gets an onDestroy call. At this moment I close the socket and stop the thread.

When Android has switched landscape mode it calls onCreate yet again and I have to do a socket re-connect. Also, all of the data the activity received needs to be downloaded once more because the server does not have the ability to know what has been sent before, i.e. there is no "resume" feature.

Thus the problem is that there is alot of data which is resent all the time when landscape mode is changed.

What are my options here?

  • Should I create a service which handles the socket traffic towards the server thus I always got all the data which the server has sent in the service.
  • Or should I disable landscape mode all together perhaps?
  • Or would my best bet be to rewrite my server which is a VERY BIG job :-)

All input is welcome :-)

/ Henrik

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

成熟稳重的好男人 2024-09-10 08:30:20

阻止您的 Activity 重新启动(Activity 在轮换 Android 上重新启动)或实现服务您的应用程序管理的。服务方法在我见过的应用程序中非常流行,并且在断开连接时允许您具有一定的灵活性。

Either prevent your activity from being restarted (Activity restart on rotation Android) or implement a Service which your application manages. The Service method is very popular with applications I have seen, and allows you some flexibility when tearing down the connection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文