Android control music with headset buttons in a service

600 views Asked by At

I'm new to Android programming and want to do the following:

I have created a background service. When I'm listening to music (standard music player on e.g. Samsung device) and the service is ACTIVE, then I want the service to listen for the headset buttons. This means:

  • When long pressing + on headset: Next Track
  • When short pressing + on headset: Louder
  • When long pressing - on headset: Last Track
  • When short pressing - on headset: Quieter

Q1. Whats the best approach to implement this behavior? Is it even possible to do it in a service?

Q2. And is there a difference between Phone Hardware Buttons +/- and Headset Buttons +/- ?

Thanks in advance.

EDIT:

In my Service.java I have the onStartCommand-Method, where I want to insert the listener:

public int onStartCommand(Intent intent, int flags, int startId){

    Toast.makeText(getApplicationContext(), "Volume control active!", Toast.LENGTH_SHORT).show();

    //Listen for the Buttons here
    //someListener(blabla);


    return START_STICKY;

}

After that Method above, I inserted per copy-paste the following Method (found on Stackoverflow)

public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        if (action == KeyEvent.ACTION_DOWN) {
            //TODO
        }
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (action == KeyEvent.ACTION_DOWN) {
            //TODO
        }
        return true;
    default:
        return super.dispatchKeyEvent(event);
    }
}

I cant test the code, because Eclipse says, that in the default case: "The method dispatchKeyEvent(KeyEvent) is undefined for the type Service"

Any suggestions?

Thanks

0

There are 0 answers