只要应用程序在屏幕上,网络线程就必须存在

发布于 2024-11-02 16:46:11 字数 375 浏览 4 评论 0原文

在我的应用程序中,我必须连接到服务器,我在一个单独的线程中执行此操作,并且我希望只要应用程序的任何活动在屏幕上可见,连接就保持活动状态。我还希望如果用户离开我的应用程序,线程就会中断并关闭连接。

这里的主要问题是,如果用户旋转屏幕,当前的 Activity 就会被破坏,我无法区分这种情况与用户真正离开我的 Activity 的情况。方法onRetainNonConfigurationInstance()不起作用,因为它是在onStop()之后调用的,而我想在onStop()中关闭连接。

我也尝试了绑定服务,但问题完全相同,旋转屏幕时服务被关闭。

而且我不想自己处理配置更改。

我该怎么办?

In my application I have to connect to a server, I’m doing this in a separate thread, and I want that the connection stays active as long as any activity of my application is visible on the screen. I also want that if the user leave my application, the thread is interrupted and the connection is closed.

The main problem here is that if the user rotate the screen, the current activity is destroyed and I cannot distinguish this situation from a situation where the user is really leaving my activity. The method onRetainNonConfigurationInstance() does not work because it is called after onStop(), and I want to shut down the connection in onStop().

I also tried a bound service but the problem is exactly the same, the service is shut down when I rotate the screen.

And I do not want to handle the configuration change myself.

How can I do?

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

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

发布评论

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

评论(2

流绪微梦 2024-11-09 16:46:11

我知道这与您不想自己处理配置更改的说法有些矛盾,但如果您添加

<activity android:name="org.example.Activity" android:configChanges="orientation|keyboardHidden"></activity>

到清单中,则不应调用生命周期方法。如果您不重写 onConfigurationChanged() 方法,则您不需要进行任何特殊处理,一切都由超类处理。

I know it contradicts a bit your statement that you don't want to handle the configuration change yourself, but if you add

<activity android:name="org.example.Activity" android:configChanges="orientation|keyboardHidden"></activity>

to your Manifest, the lifecycle methods should not get called. If you don't override the onConfigurationChanged() method, no special handling is needed from your side and everything is taken care of by the super class.

难理解 2024-11-09 16:46:11

onUserLeaveHint() 方法成功了。

The onUserLeaveHint() method did the trick.

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