在Android 4.0系统源码中,状态栏上的各个按钮在xml配置文件里加入了这样的一个属性:systemui:keyCode=“xx",比如
返回键:systemui:keyCode=“4"
Home键:systemui:keyCode=“3"
音量减键:systemui:keyCode=“25"
音量加键:systemui:keyCode=“24" 等等。
系统对这些键的处理在:framework/base/services/java/com/android/server/vm/WindowManagerService.java里进行处理:
public boolean injectKeyEvent(KeyEvent ke,boolean sync){
/**
.........
*/
调用了InputManager的injectInputEvent()方法。
}
我们如果想在应用程序里实现一个按钮点击长生返回键的作用,就可以获取利用下面的方法来进行:
private IWindowManager mWinManager = null;
private void sendKeyEvent(int keycode) {
long now;
if (mWinManager == null) {
mWinManager = IWindowManager.Stub.asInterface(ServiceManager
. getService(Context.WINDOW_SERVICE));
}
now = SystemClock.uptimeMillis();
KeyEvent event = new KeyEvent(now, now, KeyEvent.ACTION_DOWN,keycode, 0);
try {
mWinManager.injectKeyEvent(event, false);
} catch (RemoteException e) {
Log.e(TAG, "sendKey remote connect failed", e);
}
event = new KeyEvent(now, now, KeyEvent.ACTION_UP, keycode, 0);
try {
mWinManager.injectKeyEvent(event, true);
} catch (RemoteException e) {
Log.e(TAG, "sendKey remote connect failed", e);
}
}
直接调用sendKeyEvent即可。