屏幕锁定时使用音量键

时间:2012-04-27 12:33:05

标签: android

此代码不起作用将屏幕锁定。如果我想在屏幕锁定时使用音量键工作,该怎么办?

我的代码是:

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

2 个答案:

答案 0 :(得分:3)

您可以使用“android.media.VOLUME_CHANGED_ACTION”操作注册BroadcastReceiver

android.media.VOLUME_CHANGED_ACTION

其他做法是:volume key on Android

答案 1 :(得分:2)

在服务中执行此操作:

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"));
}

}

然后使用操作Intent.ACTION_SCREEN_OFF注册BroadcastReceiver,以在屏幕关闭时连续播放静音,并在屏幕打开时动作Intent.ACTION_SCREEN_ON以停止音乐。音量按钮仅在播放音乐时有效。