Google Groups

Re: [android-developers] Re: Socket sharing between activities


Dianne Hackborn Apr 17, 2012 4:26 PM
Posted in group: Android Developers
On Tue, Apr 17, 2012 at 12:03 AM, Federico Paolinelli <fede...@gmail.com> wrote:
Not using a service will make the connection "available to be killed"
if the application goes background.
Is that correct?

Yes.
 
And, if we want to close the connection when the application is no
longer visible, where should the connection be closed?
The onStop() gets called when the app goes background but also when
the activity gets destroyed because the user pressed the back button
to get to a previous activity (and in this case we don't want to close
the connection).

You just want to keep track of the number of active clients to decide when you should be running.  Have two methods:

class MyConnection {
    private mStartCount;

    void start() {
        mStartCount++;
        if (mStartCount == 1) {
            // Bring up connection
        }
    }

    void stop() {
        mStartCount--;
        if (mStartCount == 0) {
            // Bring down connection
        }
    }
}

And call these in each onStart() and onStop() of the activities that are using the connection.

--
Dianne Hackborn
Android framework engineer
hac...@android.com

Note: please don't send private questions to me, as I don't have time to provide private support, and so won't reply to such e-mails.  All such questions should be posted on public forums, where I and others can see and answer them.