Use the volume key during screen lock

This code does not work, the screen will be locked. What should I do if I want the volume key to work while the screen is 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); } } 
+1
source share
2 answers

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

 android.media.VOLUME_CHANGED_ACTION 

Another way to do this: the volume key on Android .

+3
source

Do it in the 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 the BroadcastReceiver with the Intent.ACTION_SCREEN_OFF action to continuously produce a silent sound when the screen is off, and the Intent.ACTION_SCREEN_ON action to stop the music when the screen is on. The volume buttons are active only when playing music.

+1
source

All Articles