How Can I Send Key Events In Android?
I am macking a custom navigation bar to Android 4.0.3.r1 and want to send key events like 'Home' and 'Back'. My application is not a system therefore: IWindowManager mWindowManager
Solution 1:
Here are some precision to Roman answer
BaseInputConnectionmInputConnection=newBaseInputConnection( findViewById(R.id.main_content), true);
KeyEventkd=newKeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU);
KeyEventku=newKeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU);
mInputConnection.sendKeyEvent(kd);
mInputConnection.sendKeyEvent(ku);
Solution 2:
BaseInputConnectionmInputConnection=newBaseInputConnection(targetView, true);
mInputConnection.sendKeyEvent(newKeyEvent(...));
Solution 3:
It works for me:
publicstaticvoidsimulateKey(finalint KeyCode) {
newThread() {
@Overridepublicvoidrun() {
try {
Instrumentationinst=newInstrumentation();
inst.sendKeyDownUpSync(KeyCode);
} catch (Exception e) {
Log.e("Exception when sendKeyDownUpSync", e.toString());
}
}
}.start();
}
Solution 4:
you can try this
try
{
StringkeyCommand="input keyevent " + KeyEvent.KEYCODE_MENU;
Runtimeruntime= Runtime.getRuntime();
Processproc= runtime.exec(keyCommand);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
of course, you can choose command input text ...
for input a text.
Solution 5:
None of these are valid. To go to Home screen from use below code.
Intenthome=newIntent(Intent.ACTION_MAIN);
home.addCategory(Intent.CATEGORY_HOME);
//home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(home);
If you are not calling from activity/fragment you may have to uncomment the flag part. For going back below code works on some devices.
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
Let me know if this helps!
Post a Comment for "How Can I Send Key Events In Android?"