一、给自定义按键添加广播
修改PhoneWindowManager.java中的interceptKeyBeforeDispatching方法
/frameworks/base/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@Override
public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
final boolean keyguardOn = keyguardOn();
final int keyCode = event.getKeyCode();
final int repeatCount = event.getRepeatCount();
final int metaState = event.getMetaState();
final int flags = event.getFlags();
final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
final boolean canceled = event.isCanceled();
final boolean longPress = (flags & KeyEvent.FLAG_LONG_PRESS) != 0;
final boolean virtualKey = event.getDeviceId() == KeyCharacterMap.VIRTUAL_KEYBOARD;
final String isCitKeyTest=SystemProperties.get("persist.sys.startCitKeyTest"); //添加自定义按键广播----开始
switch (keyCode)
{
case 135:
case 136:
case 137:
case 139:
{
if (repeatCount == 0) { Intent myKeyIntent = new Intent(); if(down)
{
myKeyIntent.setAction("com.rscja.android.KEY_DOWN");
}
else
{
myKeyIntent.setAction("com.rscja.android.KEY_UP");
} myKeyIntent.putExtra("keycode", keyCode); mContext.sendBroadcastAsUser(myKeyIntent, UserHandle.ALL); }
} break;
} //添加自定义按键广播----结束 ……
……
……
…… }
二、通过广播给当前焦点输入框赋值
修改InputMethodService.java中的onCreate()方法
/frameworks/base/core/java/android/inputmethodservice/InputMethodService.java
@Override public void onCreate() {
mTheme = Resources.selectSystemTheme(mTheme,
getApplicationInfo().targetSdkVersion,
android.R.style.Theme_InputMethod,
android.R.style.Theme_Holo_InputMethod,
android.R.style.Theme_DeviceDefault_InputMethod,
android.R.style.Theme_DeviceDefault_InputMethod);
super.setTheme(mTheme);
super.onCreate();
mImm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
mInflater = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mWindow = new SoftInputWindow(this, "InputMethod", mTheme, null, null, mDispatcherState,
WindowManager.LayoutParams.TYPE_INPUT_METHOD, Gravity.BOTTOM, false);
if (mHardwareAccelerated) {
mWindow.getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
}
initViews();
mWindow.getWindow().setLayout(MATCH_PARENT, WRAP_CONTENT); //注册广播监听
IntentFilter barCodeCheckFilter = new IntentFilter("com.rscja.android.DATA_RESULT");
mRootView.getContext().registerReceiver(m_barCodeCheckReciever,barCodeCheckFilter); } //添加自定义广播
private BroadcastReceiver m_barCodeCheckReciever = new BroadcastReceiver () { @Override
public void onReceive(Context context, Intent intent) {
InputConnection conn = getCurrentInputConnection(); String intent_data=intent.getStringExtra("data"); if(intent_data.charAt(intent_data.length() - 1)=='\n')
{
if (conn != null) {
conn.commitText(intent_data.substring(0,intent_data.length()-1), 1);
}
sendKeyChar('\n');
}
else
{
if (conn != null) {
conn.commitText(intent_data, 1);
}
}
}
};