在android上的activity之间保持socket连接
我正在 android 3.1 上开发一个应用程序,我有一个 Activity A,它有一个从 aSyncTask 扩展的子类,该子类创建一个套接字并连接到服务器。我所有的沟通都很好。我收到消息并向服务器发送命令,但是当我收到特定命令时,我必须启动第二个活动(活动 B),但我不能丢失我的套接字并与服务器建立通信,而且我仍然能够从活动 B 接收命令并将其发送到服务器。我怎样才能做到这一点? 请帮忙!
I'm developing an application on android 3.1 and I have an Activity A that has a subclass extending from aSyncTask, this subclass create a socket and connect to a server. All my communication is good. I received messages and send commands to a server, but when I got a specific command I have to start a second activity (activity B) but I can't lost my socket and the establish communication with the server, plus I have to still able to receive and send commands from activity B to server. How can I do that??
Any help please!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 Dianne Hackborn(Android 工程师)的说法,在活动之间传递网络连接的推荐做法是创建一个单例,任何活动都可以从那里访问和管理连接。请参阅此处并查看 Dianne 的第一篇博文。
Android 开发者网站上的 Services 页面(“Basics”下的附注' 部分)还提到,只有当您的应用程序在后台时需要运行需要继续执行的代码时,您才应该使用服务。
According to Dianne Hackborn (Android engineer), the recommended practice to pass network connections between activities is to create a singleton that any activity can access and manage the connection from there. See here and check the first post by Dianne.
The Services page on the android developers site (side note under the 'Basics' Section) also mentions that you should only use a service if you need to run code that needs to continue execution while your application is in the background.
我的方法是实现一个 服务 并将所有网络连接代码移动/集中到服务中,供所有人使用想要使用套接字连接的活动,请在 onCreate() 中绑定您的网络服务,然后在 onDestory() 中完成后取消绑定它
My approach is implementing a service and move/centralise all your network connection code into service, for all activities that want to use socket connection, bind your network service in onCreate() then after finish unbind it in onDestory()