Android 长按音量加键变成上一曲,音量减键变成下一曲

长按音量加键变成上一曲,音量减键变成下一曲

实现原理看注释
frameworks/base/services/core/java/com/android/server/policy/PhoneWindowManager.java

//add by fengzc
boolean mVolUpConsumed;
boolean mVolUpSendBySelf;/
boolean mVolDownConsumed;
boolean mVolDownSendBySelf;
//end by fengzc

/** {@inheritDoc} */
    @Override
public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int 
policyFlags) {
        final boolean keyguardOn = keyguardOn();
        ....
       else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP
                || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
                || keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
            if (mUseTvRouting) {
                // On TVs volume keys never go to the foreground app.
                dispatchDirectAudioEvent(event);
                return -1;
            }
			//add by fengzc 长按音量加键为上一曲,音量减键为下一曲
			if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			if (down) {
				if (repeatCount == 0) {
					if (!mVolUpSendBySelf) {
						//用户短按下down时不分发该事件,等up时,自己模拟发送一个音量加键事件
						//这样避免长按音量加键时也会触发音量加键,导致音量调节窗口弹出
						return -1;
					}
				} else if (repeatCount == 11) {//时间差不多就是500ms长按事件
					mVolUpConsumed = true;
					//模拟发送上一曲事件
					sendNoahKeyCode(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
					return -1;
				} else {
					return -1;
				}
			} else {
				if (mVolUpConsumed) {
					mVolUpConsumed = false;
					return -1;
				} else {
					if (!mVolUpSendBySelf) {
						//自己模拟发送一个音量加键事件
						sendNoahKeyCode(KeyEvent.KEYCODE_VOLUME_UP);
						mVolUpSendBySelf = true;
					} else {
						mVolUpSendBySelf = false;
					}
				}
			}
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
			if (down) {
				if (repeatCount == 0) {
					if (!mVolDownSendBySelf) {
						return -1;
					}
				} else if (repeatCount == 11) {
					mVolDownConsumed = true;
					sendNoahKeyCode(KeyEvent.KEYCODE_MEDIA_NEXT);
					return -1;
				} else {
					return -1;
				}
			} else {
				if (mVolDownConsumed) {
					mVolDownConsumed = false;
					return -1;
				} else {
					if (!mVolDownSendBySelf) {
						sendNoahKeyCode(KeyEvent.KEYCODE_VOLUME_DOWN);
						mVolDownSendBySelf = true;
					} else {
						mVolDownSendBySelf = false;
					}
				}
			}
		}
		//end by fengzc
        } 
....

///add by fengzc 模拟按键发送
private void sendNoahKeyCode(final int keyCode){  
        new Thread () {  
            public void run() {  
                try {  
                    Instrumentation inst = new Instrumentation();  
                    inst.sendKeyDownUpSync(keyCode);  
                } catch (Exception e) {  
                    Log.e("Exception when sendNoahKeyCode", e.toString());  
                }  
            }  
        }.start();  
    }
///end by fengzc                

你可能感兴趣的:(Android,framework,android,framework)