views:

46

answers:

1

I have a service running (Socket), this is how i start the service.

Intent s = new Intent(this, Socket.class);
startService(s);

in every activity i check for the user to select the home button, as soon as the home button is clicked i need to destroy the socket, so i have the below code on every activity in my app:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{       
    if (keyCode == KeyEvent.KEYCODE_HOME)
    {
        Intent s = new Intent(this, Socket.class);
        stopService(s);
    }   
    return true;
}

but this doesn't seem to stop my service?
Am i missing something? I need to destroy my service as soon as the home button is clicked.

+1  A: 

Instead of hooking into keypress events and such, perhaps working with the built-in events like onPause, onStart, onDestroy, etc is more suited to your needs?

Another question on StackOVF recently had a brilliant reply with a flowchart that can help you figure out where to start/stop any other stuff you're using:

http://developer.android.com/images/activity_lifecycle.png

creds to monoceres for posting that in this topic:

http://stackoverflow.com/questions/3479433/app-crashes-after-receving-phone-call

LuCHEF