Android(安卓)代码中实现返回键功能
16lz
2022-04-02
代码里实现返回键
刚才自己的项目里用到了
有两种办法:
- 采用
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 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); } }
更多相关文章
- Android实现定时器的方法
- Android实现对imageview的拖动以及缩放
- android SQLiteOpenHelper 对SQLite的操作
- Android实现两次按下返回键退出
- Android与Js交互获取返回值
- Android三种实现定时器的方法
- Android(安卓)Service 之 Bound Services
- Android实现模拟点击的一种方法
- 浅谈Java中Collections.sort对List排序的两种方法