只要应用程序在屏幕上,网络线程就必须存在
在我的应用程序中,我必须连接到服务器,我在一个单独的线程中执行此操作,并且我希望只要应用程序的任何活动在屏幕上可见,连接就保持活动状态。我还希望如果用户离开我的应用程序,线程就会中断并关闭连接。
这里的主要问题是,如果用户旋转屏幕,当前的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道这与您不想自己处理配置更改的说法有些矛盾,但如果您添加
到清单中,则不应调用生命周期方法。如果您不重写 onConfigurationChanged() 方法,则您不需要进行任何特殊处理,一切都由超类处理。
I know it contradicts a bit your statement that you don't want to handle the configuration change yourself, but if you add
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.
onUserLeaveHint()
方法成功了。The
onUserLeaveHint()
method did the trick.