Search code examples
androidandroid-activityjava-websocket

Android: keep activity working while in backstack


I have an chat app that goes like this :

Activity A ( main screen showing some general stuff)

Activity B ( chat room where user can send and receive messages using a WebSocket. I made websocket global, instantiated/reconnected in B, and singleton, since putting in Service seems to be a problem - not reliable, restarting sometimes where the socket it holds becomes null etc. and needs reinitialized etc.)

Activity C ( user navigates here from B, by clicking on menu. C shows list of participants, owner of the room can kick someone out etc.)

So, when I am in C, I have arrived as A-> B -> C.

When I am in C, I still want B to continue receiving messages, processing them, putting them in messagesadapter etc. That is because, we dont want to lose chat messages ( which are processed in B) while in screen C.

Question - when I am in C, will B functionality keep working ? I want to make sure it works. What do I need to ensure it happens reliably ?


Solution

  • Question - when I am in C, will B functionality keep working ? I want to make sure it works. What do I need to ensure it happens reliably ?

    To answer your question, your Activity B is alive in the task and asynchronous code in that Activity will continue to run. Just because the Activity is "paused" does not mean that methods cannot be called on it. It is still a live object.

    If you only want your chat active when the user has your application in the foreground, then you can do it the way you have described. As soon as your application goes to the background (on arrival of an incoming call, for example), Android can kill the process without warning. When the user returns to your app, Android will create a new process for it and Activity C will be reinstantiated. However, Activity B will not be reinstantiated.

    However, you really need a Service to handle socket connections, as it is much more stable.