Android 实现模拟按键方法

通过Runtime实现,代码如下:
[html]view plain copy

  1. try
  2. {
  3. String keyCommand = "input keyevent " + KeyEvent.KEYCODE_MENU;
  4. Runtime runtime = Runtime.getRuntime();
  5. Process proc = runtime.exec(keyCommand);
  6. }
  7. catch (IOException e)
  8. {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. }
这个代码是模拟菜单键,模拟其它按键只需将KeyEvent.KEYCODE_MENU替换成其它键值。

缺点:反应速度较慢

以下附带各KeyCode值:
【Android 实现模拟按键方法】
[html]view plain copy
  1. KEYCODE_UNKNOWN=0;
  2. KEYCODE_SOFT_LEFT=1;
  3. KEYCODE_SOFT_RIGHT=2;
  4. KEYCODE_HOME=3;
  5. KEYCODE_BACK=4;
  6. KEYCODE_CALL=5;
  7. KEYCODE_ENDCALL=6;
  8. KEYCODE_0=7;
  9. KEYCODE_1=8;
  10. KEYCODE_2=9;
  11. KEYCODE_3=10;
  12. KEYCODE_4=11;
  13. KEYCODE_5=12;
  14. KEYCODE_6=13;
  15. KEYCODE_7=14;
  16. KEYCODE_8=15;
  17. KEYCODE_9=16;
  18. KEYCODE_STAR=17;
  19. KEYCODE_POUND=18;
  20. KEYCODE_DPAD_UP=19;
  21. KEYCODE_DPAD_DOWN=20;
  22. KEYCODE_DPAD_LEFT=21;
  23. KEYCODE_DPAD_RIGHT=22;
  24. KEYCODE_DPAD_CENTER=23;
  25. KEYCODE_VOLUME_UP=24;
  26. KEYCODE_VOLUME_DOWN=25;
  27. KEYCODE_POWER=26;
  28. KEYCODE_CAMERA=27;
  29. KEYCODE_CLEAR=28;
  30. KEYCODE_A=29;
  31. KEYCODE_B=30;
  32. KEYCODE_C=31;
  33. KEYCODE_D=32;
  34. KEYCODE_E=33;
  35. KEYCODE_F=34;
  36. KEYCODE_G=35;
  37. KEYCODE_H=36;
  38. KEYCODE_I=37;
  39. KEYCODE_J=38;
  40. KEYCODE_K=39;
  41. KEYCODE_L=40;
  42. KEYCODE_M=41;
  43. KEYCODE_N=42;
  44. KEYCODE_O=43;
  45. KEYCODE_P=44;
  46. KEYCODE_Q=45;
  47. KEYCODE_R=46;
  48. KEYCODE_S=47;
  49. KEYCODE_T=48;
  50. KEYCODE_U=49;
  51. KEYCODE_V=50;
  52. KEYCODE_W=51;
  53. KEYCODE_X=52;
  54. KEYCODE_Y=53;
  55. KEYCODE_Z=54;
  56. KEYCODE_COMMA=55;
  57. KEYCODE_PERIOD=56;
  58. KEYCODE_ALT_LEFT=57;
  59. KEYCODE_ALT_RIGHT=58;
  60. KEYCODE_SHIFT_LEFT=59;
  61. KEYCODE_SHIFT_RIGHT=60;
  62. KEYCODE_TAB=61;
  63. KEYCODE_SPACE=62;
  64. KEYCODE_SYM=63;
  65. KEYCODE_EXPLORER=64;
  66. KEYCODE_ENVELOPE=65;
  67. KEYCODE_ENTER=66;
  68. KEYCODE_DEL=67;
  69. KEYCODE_GRAVE=68;
  70. KEYCODE_MINUS=69;
  71. KEYCODE_EQUALS=70;
  72. KEYCODE_LEFT_BRACKET=71;
  73. KEYCODE_RIGHT_BRACKET=72;
  74. KEYCODE_BACKSLASH=73;
  75. KEYCODE_SEMICOLON=74;
  76. KEYCODE_APOSTROPHE=75;
  77. KEYCODE_SLASH=76;
  78. KEYCODE_AT=77;
  79. KEYCODE_NUM=78;
  80. KEYCODE_HEADSETHOOK=79;
  81. KEYCODE_FOCUS=80; //*Camera*focus
  82. KEYCODE_PLUS=81;
  83. KEYCODE_MENU=82;
  84. KEYCODE_NOTIFICATION=83;
  85. KEYCODE_SEARCH=84;
  86. KEYCODE_MEDIA_PLAY_PAUSE=85;
  87. KEYCODE_MEDIA_STOP=86;
  88. KEYCODE_MEDIA_NEXT=87;
  89. KEYCODE_MEDIA_PREVIOUS=88;
  90. KEYCODE_MEDIA_REWIND=89;
  91. KEYCODE_MEDIA_FAST_FORWARD=90;
  92. KEYCODE_MUTE=91;

    推荐阅读