我有一个这样的聊天应用程序:
Activity A(主屏幕显示一些常规内容)
Activity B(用户可以使用 WebSocket 发送和接收消息的聊天室。我将 websocket 设置为全局的,在 B 中实例化/重新连接,并且单例,因为放入 Service 似乎是一个问题 - 不可靠,有时会重新启动它持有的套接字变为空等并且需要重新初始化等)
Activity C(用户通过单击菜单从 B 导航到此处。C 显示参与者列表,房间所有者可以将某人踢出等)
所以,当我在 C 时,我已经到达 A-> B -> C。
当我在C中时,我仍然希望B继续接收消息,处理它们,将它们放入消息适配器等。这是因为,我们不想在屏幕C中丢失聊天消息(在B中处理)。
问题 - 当我在 C 中时,B 功能会继续工作吗?我想确保它有效。我需要什么来确保它可靠地发生?
最佳答案
当您处于 C 时, Activity B 将暂停
Google 提及
Activity Lifecycle
Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.
为了实现你想要的,你需要一个在后台运行的IntentService,并且你必须在 Activity B中注册一个广播接收者来从IntentService,然后在 Activity B 的 onResume 方法中,您可以使用来自广播接收器的最新消息更新 UI。
关于Android:在后台堆栈中保持 Activity 正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39757552/