Q:

Use volume key while screen locked

This code doesn't work will screen locked. what should I do if I want volume key work while screen locked? 
My code is :
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    int action = event.getAction();
    int keyCode = event.getKeyCode();
        switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_UP:
            if (action == KeyEvent.ACTION_UP) {
                //TODO
            }
            return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            if (action == KeyEvent.ACTION_DOWN) {
                //TODO
            }
            return true;
        default:
            return super.dispatchKeyEvent(event);
        }
    }

A:

you can register BroadcastReceiver with action "android.media.VOLUME_CHANGED_ACTION" :
android.media.VOLUME_CHANGED_ACTION

Other way of doing is:  volume key on Android .

A:

Do this in a service:
public class MyService extends Service {

@Override
public void onCreate() {
    super.onCreate();
    final BroadcastReceiver vReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
             //your code here
        }
    };
    registerReceiver(vReceiver, new IntentFilter("android.media.VOLUME_CHANGED_ACTION"));
}

}

Then register BroadcastReceiver with action Intent.ACTION_SCREEN_OFF to play a silent sound continuously when screen is off and action Intent.ACTION_SCREEN_ON to stop music when screen on. Volume buttons are only active when there's music playing.

