How to handle activity life cycle involving sockets in Android?

Posted by Henrik on Stack Overflow See other posts from Stack Overflow or by Henrik
Published on 2010-05-30T18:56:06Z Indexed on 2010/05/30 19:02 UTC
Read the original article Hit count: 336

Hello all,

  • I have an Android activity which in turn starts a thread.
  • In the thread I open a persistent TCP socket connection.
  • When the socket connects to the server dynamic data is downloaded.
  • The thread sends messages using Handler-class to the activity when data has been received.

Now if the user happens to switch from portrait to landscape mode the activity gets an onDestroy call. At this moment I close the socket and stop the thread.

When Android has switched landscape mode it calls onCreate yet again and I have to do a socket re-connect. Also, all of the data the activity received needs to be downloaded once more because the server does not have the ability to know what has been sent before, i.e. there is no "resume" feature.

Thus the problem is that there is alot of data which is resent all the time when landscape mode is changed.

What are my options here?

  • Should I create a service which handles the socket traffic towards the server thus I always got all the data which the server has sent in the service.
  • Or should I disable landscape mode all together perhaps?
  • Or would my best bet be to rewrite my server which is a VERY BIG job :-)

All input is welcome :-)

/ Henrik

© Stack Overflow or respective owner

Related posts about android

Related posts about sockets