1

How can i stop services which is running on background. Is there any way to do it using Back and home button press

I have tried to do it using key events but still it's not working. Here you can check my code below ...

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_HOME)) {          
        stopBackgroundAudio();// background services 
        return true;
    }
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {           
        stopBackgroundAudio();
        return true;
    }
    if ((keyCode == KeyEvent.KEYCODE_MENU)) {            
        stopBackgroundAudio();
        return true;
    }
     return super.onKeyDown(keyCode, event);

}

Help me with this or suggest me other option to stop service?

SourabhTech
  • 1,357
  • 12
  • 17
  • These key are handled by Android OS. But you can use it using reflection. See http://stackoverflow.com/a/31872330/3496570 – Zar E Ahmer Aug 07 '15 at 07:51

2 Answers2

1

Back and home don't use that API. THe back key comes in via the backButtonPressed function, which you can override. The home button doesn't come up ever- your app just gets pushed to the background.

Also, if you want the audio to stop when you're put int he background, just stop it in onPause.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch(keyCode)
        {
        case KeyEvent.KEYCODE_HOME:
        stopBackgroundAudio();// background services 
            return true;
        case KeyEvent.KEYCODE_BACK:
         stopBackgroundAudio();
            return true;
        case KeyEvent.KEYCODE_MENU:
       stopBackgroundAudio();
            return true;


        }

       return super.onKeyDown(keyCode, event);
    }

i am not sure yours service is a bind or unbind service, if it is unbind service than it may be a problem and also if it is a bind service than have a proper implementation!!

Jitesh Upadhyay
  • 5,244
  • 2
  • 25
  • 43