0

我想用音量键改变屏幕的亮度。我使用了这段代码,但它不起作用:

@Override
    public boolean onKeyDown(int keyCode,KeyEvent keyEvent){
        WindowManager.LayoutParams layout = getWindow().getAttributes();

        if(keyEvent.getAction() == KeyEvent.ACTION_DOWN){
            switch (keyCode){
                case KeyEvent.KEYCODE_VOLUME_DOWN:
                    layout.screenBrightness -= 0.1;
                    getWindow().setAttributes(layout);
                    break;
                case KeyEvent.KEYCODE_VOLUME_UP:
                    layout.screenBrightness += 0.1;
                    getWindow().setAttributes(layout);
                    break;
            }

        }
        return super.onKeyDown(keyCode , keyEvent);
    }

当我按音量键向下/向上时,铃声音量会改变吗?

4

2 回答 2

3

试试这个:

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

它来自这里。下次尝试更好地搜索。

于 2013-07-08T08:19:55.553 回答
1
@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) {

                brightness+=10;
            if (brightness > 100) brightness = 100;
        }
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (action == KeyEvent.ACTION_DOWN) {
            brightness-=10;
            if (brightness < 0) brightness=0;
        }
        return true;
    default:
        return super.dispatchKeyEvent(event);
    }
}

功能

private void setBrightness() {
  Window w = getWindow();
  WindowManager.LayoutParams lp = w.getAttributes();
  lp.screenBrightness = (float)brightness/100;
  if (lp.screenBrightness<.01f) lp.screenBrightness=.01f;
  w.setAttributes(lp);
  updateTextLabel();
}
于 2013-07-08T08:42:19.013 回答