4
@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);
        }
    }

此代码在屏幕打开时有效。但不是在屏幕锁定时。屏幕锁定时有没有办法获取音量键事件?

4

1 回答 1

3

该事件仅在屏幕打开时触发。否则需要 root 权限。

制作一个 BroadcastReceiver 扩展类

 public class YourBoardcastReceiver extends BroadcastReceiver {
                @Override
                public void onReceive(Context context, Intent intent) {


Log.e("get something", "i dont know what!!");

        String intentAction = intent.getAction();
        KeyEvent event = null;
        if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
            event = (KeyEvent) intent
                    .getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        }

        if (event == null) {
            return;
        }

        int keycode = event.getKeyCode();
        int action = event.getAction();
        long eventtime = event.getEventTime();

        if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
                || keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
            if (action == KeyEvent.ACTION_DOWN) {
                // Start your app here!

                // ...
                Log.e("event/////", "Trigerd");

                if (isOrderedBroadcast()) {
                    abortBroadcast();
                }
            }
        }
    }
                }
        }

在你的清单中:

<receiver android:name="YourBoardcastReceiver">
                <intent-filter>
                        <action android:name="android.intent.action.SCREEN_ON" />
                </intent-filter>
</receiver>

并这样称呼它。

mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mRemoteControlResponder = new ComponentName(getPackageName(),
            YourBoardcastReceiver.class.getName());
于 2013-04-23T10:14:09.110 回答