Robert3452
Robert3452

Reputation: 1476

Android Application Close Connection in Background Thread

I have an android application. It opens an internet connection to a server on another machine. The server sends regular status updates back to the android application The application has multiple activities and must pass over the same open connection between each activity.

Having a custom Application object which holds the connection fits this scenario very well

BUT: When my application exits I want to close the connection, terminate the threads and stop receiving these updates from the server. However I have read article after article explaining that Android apps don't exit and it is impossible to get a terminate event/message/signal.

How does anyone ever close a connection in an Android application? How do I stop my threads and stop wasting battery?

Upvotes: 0

Views: 956

Answers (1)

Robert3452
Robert3452

Reputation: 1476

The method I have found to achieve this is to create a service that counts bindings to itself. I then make each activity bind to the service. If the service notices that it has 0 bindings it waits a certain amount of time and then terminates.

I have fully documented my approach here: https://code.metcarob.com/node/201

I am not completely happy with it but it is the best solution I can find.

Upvotes: 1

Related Questions