Take the 2-minute tour ×

I'm wondering what is considered best practice for the following case:

I need to keep open a socket in my android client that listens to messages it gets from the server and notifies the user with a toast message.

My first thought went to using a singleton and storing the client I use to communicate with the server there:

This way I can send a message using:


A problem I will probably encounter here is doing something in the activity when the socket receives an incoming message.

One way of handling it would be something like this in an Activity:

MySingletonHere.getInstance().setMessageHandler(new MessageHandler() {
    public String handleMessage(String m) {
        Toast.make ...

What I would like to ask is if this is considered a "good" solution because it doesn't feel like one. There probably is an android component that could handle this kind of situation. I don't know much about android development but if I understand correctly a service should be able to perform something like this?


share|improve this question
Have you considered [C2DM](code.google.com/android/c2dm/)? –  Phil Mar 9 '12 at 22:36
We have considered C2DM but it's a small school project and the push notifications aren't the most important part so we quickly wrote our own simple server / client. The communication works, I was just curious about what most people use to handle background messages like this (not necessarily push notifications). –  geoffreydv Mar 9 '12 at 22:43
add comment

1 Answer

If these messages only matter while the one-and-only activity that cares about the messages is in the foreground, just have the activity handle the socket itself.

Beyond that, though, you need a service, simply because Android will be getting rid of your process otherwise. So long as the service will run for a fairly short time, or is very obviously under the user's control (and you also use startForeground()), this will work.

share|improve this answer
add comment

Your Answer


