I'm currently writing my first Android app which will ping game servers, check whether they are online, and alert the user if they are offline. The app also displays each servers status on the main activity. In order to do this, I made a indefinitely running service that loops through a static list of server objects (it's static because there will only ever be one instance of the service), pings the server, and then changes the servers status to online/offline. For the main activity, I've created a timer that also loops through that list, checks the status of the server, and then changes the TextView for the server to online/offline. The reason why I've made a separate timer for updating the UI is because I only want it to run when the main activity is visible. Is there a better way to do this?
2 Answers
If you only want to run it when the main activity is visible, then implement a method to do that. Example: How to detect when an Android app goes to the background and come back to the foreground
Then for the "static list of server objects" I would be careful with static stuff, it's usually not a good idea (and it's "technically slower" to access static members).
For the "timer" don't do that. Instead have your Service broadcast an intent (or if you bind it, have your activity implement a custom interface that the server can talk to in a typical observer/listener pattern).
E.g.:
public interface ServerStatusListener {
void onServerIsUp();
void onServerIsDown();
}
If you go the Broadcast Intent route, have a small Broadcast Receiver in your base activity that listens to this:
public class ServerStatusReceiver extends BroadcastReceiver {
public void onReceive(final Context context, final Intent intent) {
// analyze the intent and determine what happened
// pseudo code
if (intent.getBooleanExtra("com.your.app.EXTRA_NETWORK_IS_UP", false) ) {
serviceIsUp();
} else {
serviceIsDown();
}
}
}
You get the idea. Both approaches are ok. Different concepts. Remember that the onReceive method is already running on the UI thread, don't perform expensive stuff there.
Read the Android documentation about services, broadcast receivers, etc. It's good material and you will want to know this if you're going to be an Android developer.
Have fun!

- 1
- 1

- 26,875
- 19
- 106
- 144
You can consider a broadcast receiver. Your service can send a broadcast every time it has finished it's action, then you main activity can subscribe to this broadcast and modify the UI every time a broadcast is received.
Broadcast is easily scalable. If you ever want to add another activity which would monitor the status of the service, then the other activity would just subscribe to the same action.

- 5,287
- 5
- 39
- 44