Berkay Aras
Berkay Aras

Reputation: 127

Android long-during TCP socket connection failure after some time

i'm writing a client-server application which uses TCP socket connection. In my android project, Service creates a thread for listening the TCP socket.

Everything seems OK. But i have got one problem.. My network service running in background fine; But some time later (10-15 min..), when i try to open my application (main activity) again, I can't get responses from the socket connection. It freezes or something?? i cant send or get TCP messages from the socket.. What can be the reason of this? I'm working on my phone, via 3G connection.

(Besides, the app running in the emulator hasn't got such this problem; I assume Its connection is stable, long-during )

Thank you for your answering.

Upvotes: 2

Views: 3598

Answers (3)

fredcrs
fredcrs

Reputation: 3621

Are you sending data from time to time? Like implementing a heartbeat protocol ? if you are not, you should...or maybe it has to do with socket READ/WRITE TIMEOUT

Upvotes: 0

Bram P.
Bram P.

Reputation: 96

Due to power optimizations and perhaps changes in connectivity (GPRS/HSDPA/Wifi) it's very likely your connection is being dropped.

In order to maintain a connection, your background service needs to claim a wakelock using the PowerManager class. This prevents the device from going to power-saving mode and thus disconnecting your socket. But beware, this significantly lowers the battery life of the device.

Also, you need to handle changes in connectivity which break your open connection. Android sends out a broadcast message named android.net.conn.CONNECTIVITY_CHANGE to notify of changes in connectivity.

Depending on your use-case I would poll with when the device is in the sleep-mode and only build a connection when the device is actively in use or just use C2DM push notifications

Upvotes: 1

Kristian Evensen
Kristian Evensen

Reputation: 1345

When I have experienced something like this in my apps, it has usually been because of power optimisations on the phone (which cant be overridden). If the socket has been idle for too long, it is automatically closed and needs to be reopened.

Upvotes: 0

Related Questions