代码里实现返回键
刚才自己的项目里用到了
有两种办法:
- 采用
Runtime
/**
* Allows Java applications to interface with the environment in which they are running. Applications can not create an instance of this class, but they can get a singleton instance by invoking getRuntime()
*/
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);
} catch (IOException e) {
e.printStackTrace();
}
- 采用
Instrumentation
(注意此方法不能再主线程中)
/**
* Base class for implementing application instrumentation code. When running with instrumentation turned on, this class will be instantiated for you before any of the application code, allowing you to monitor all of the interaction the system has with the application. An Instrumentation implementation is described to the system through an AndroidManifest.xml's <instrumentation> tag.
*/
new Thread(){
@Override
public void run() {
Instrumentation ins = new Instrumentation();
ins.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
}
}.start();
若想在返回的时候干点别的
重写onKeyDown
,实现对返回键的监听
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//do something
return false;
} else {
return super.onKeyDown(keyCode, event);
}
}