Im new to Android programming, my app is supposed create a socket in order to maintain constant contact with a server (get status and updates etc) while the user changes to different activities while using the app in general.
Im wondering how its possible for the user to change to different activity classes while still have a constant connection to the server.
I though maybe in main activity to create some background handler that always runs even if the player changes to a different activity.
That handler would be the entity that would maintain contact with the server, like a sort of background task, and also communicate status to show in whatever activity that happen to be running at the time.
something like
OnCreate(....)
{
handler=new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
tick();
handler.postDelayed(this,1000);
}
},1000);
}
void tick()
{
communicate with server
}
But what if the user changes to a different activity, does the handler still run? Can the socket still receive data from server even when a different activity is running if i set up some kind of socket call back that calls a function when it gets data, but that call back would be in the main activity, how can it get called if another activity is active?
Also how to communicate new information gotten from the socket to any activity that happens to be running as to update its UI. I would imagine having a data structure that all activities can access, that is populated by the thread or whatever is communicating with the server.
It seems pretty complicated, anybody have example or know the standard way to do it?
Thanks