最新在做TV项目,涉及到模拟按键操作,这里做一下笔录:
package com.lsj.keyboardsample;
import android.app.Activity;
import android.app.Instrumentation;
import android.os.Bundle;
import android.view.KeyEvent;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// sendKeyCode1(KeyEvent.KEYCODE_MEDIA_STOP);
sendKeyCode2(KeyEvent.KEYCODE_VOLUME_DOWN);
}
/**
* 用Runtime模拟按键操作
*
* @param keyCode
* 按键事件(KeyEvent)的按键值
*/
private void sendKeyCode1(int keyCode) {
try {
// 按键操作命令 11.24勘误,之前错误的写成了"input keycode"
String keyCommand = "input keycode " + keyCode;
// 调用Runtime模拟按键操作
Runtime.getRuntime().exec(keyCommand);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* <pre>
* 使用Instrumentation接口:对于非自行编译的安卓系统,无法获取系统签名,只能在前台模拟按键,不能后台模拟
* 注意:调用Instrumentation的sendKeyDownUpSync方法必须另起一个线程,否则无效
* @param keyCode
* 按键事件(KeyEvent)的按键值
* </pre>
*/
private void sendKeyCode2(final int keyCode) {
new Thread(new Runnable() {
@Override
public void run() {
try {
// 创建一个Instrumentation对象
Instrumentation inst = new Instrumentation();
// 调用inst对象的按键模拟方法
inst.sendKeyDownUpSync(keyCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
/**
* <pre>
* 此方法使用反射调用系统IWindowManager隐藏API:兼容性较差,稳定性不好,容易出错。另外实际编译时发生错误,原因暂时不明。
* 暂时还未掌握Java的反射机制,留待以后测试
* @param keyCode
* </pre>
*/
private void sendKeyCode3(int keyCode) {
/*此方法中那个的IWindowManager是不存在的,需要使用Java的反射机制才能实现*/
/**
final int keyCode = key;
Thread sendKeyDelay = new Thread(){
public void run() {
try {
Thread.sleep(100);
long now = SystemClock.uptimeMillis();
KeyEvent keyDown = new KeyEvent(now, now, KeyEvent.ACTION_DOWN,
keyCode, 0);
IWindowManager wm = IWindowManager.Stub.asInterface(
ServiceManager.getService("window"));
wm.injectKeyEvent(keyDown, false);
KeyEvent keyUp = new KeyEvent(now, now, KeyEvent.ACTION_UP,
keyCode, 0);
wm.injectKeyEvent(keyUp, false);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
sendKeyDelay.start();
*/
}
}