views:

42

answers:

1

I have an application that uses sockets to connect to my server. A lot of times the application lies "dormant" when it doesn't need to send info back and forth to the server. When that happens, occasionally it will disconnect.

How can I determine when the socket has disconnected and then try to re-establish a connection?

I've used some applications that do exactly this and will pop up a dialog box that indicates "reconnecting". I'm sure I could code this in with some kind of "ping" method that fires every X number of seconds, but I'm wondering if the socket class has something built in that these other apps are using?

A: 

Are you using a Service to handle this Socket connection to your server (it would probably be a good idea). If/when you are, you can create the "ping" method as a thread in your service.

fredley
I do not believe I am using a service. I just have a class that I wrote that creates a new socket on a different thread and listens for incoming messages that posts to a runnable to update the UI in the main activity. Can you point me in the direction of how to set up a socket in a service for android?
Kyle
Have a look in the docs:http://developer.android.com/reference/android/app/Service.html#WhatIsAServicehttp://developer.android.com/reference/android/app/Service.html
fredley
fredley, I looked over the docs (albeit briefly) but I'm confused as to what advantages putting the socket into a service is going to give me? You suggest that it "would be a good idea"...buy why?
Kyle
If you create a thread in your activity, a new thread will be created for every activity. Using a service there's always just the one instance of the socket connection, making it much easier to manage.
fredley