Android BroadCastReceiver 用于音量键上下

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12561142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:00:25  来源:igfitidea点击:

Android BroadCastReceiver for volume key up and down

androidandroid-intentvolume

提问by malik M

If a user presses volume key up or down is it possible to detect it in my broadcast receiver? I need the full code.

如果用户向上或向下按音量键,是否可以在我的广播接收器中检测到它?我需要完整的代码。

Here is my Intent filter

这是我的意图过滤器

IntentFilter filter = new IntentFilter();
filter.addAction("android.media.VOLUME_CHANGED_ACTION");

and my onReceivemethod is

我的onReceive方法是

public void onReceive(Context arg0, Intent intent) {
      KeyEvent ke = (KeyEvent)intent.getExtras().get(Intent.EXTRA_KEY_EVENT);
        if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
                System.out.println("I got volume up event");
         }else if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
                System.out.println("I got volume key down event");
         }
    }

It gives me a null KeyEvent... any idea?

它给了我一个空的 KeyEvent ......知道吗?

回答by Theus

The intent does not have an EXTRA_KEY_EVENT extra. It does have an extra android.media.EXTRA_VOLUME_STREAM_VALUE which contains the new volume.

该意图没有额外的 EXTRA_KEY_EVENT。它确实有一个额外的 android.media.EXTRA_VOLUME_STREAM_VALUE 包含新卷。

int volume = (Integer)intent.getExtras().get("android.media.EXTRA_VOLUME_STREAM_VALUE");

If you store the old value, you can infer whether volume up or down was pressed.

如果您存储旧值,您可以推断是否按下了增大或减小音量。