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) {
                //TODO
            }
            return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            if (action == KeyEvent.ACTION_DOWN) {
                //TODO
            }
            return true;
        default:
            return super.dispatchKeyEvent(event);
        }
    }
4

2 回答 2

3

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

android.media.VOLUME_CHANGED_ACTION

其他方法是: Android 上的音量键

于 2012-04-27T12:50:19.737 回答
3

在服务中执行此操作:

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

}

然后注册 BroadcastReceiver 与动作Intent.ACTION_SCREEN_OFF,当屏幕关闭时连续播放无声的声音,并Intent.ACTION_SCREEN_ON在屏幕打开时停止音乐的动作。音量按钮仅在播放音乐时激活。

于 2016-06-28T07:26:49.707 回答