代码里实现返回键

刚才自己的项目里用到了
有两种办法:

  • 采用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);        }    }

更多相关文章

  1. Android实现定时器的方法
  2. Android实现对imageview的拖动以及缩放
  3. android SQLiteOpenHelper 对SQLite的操作
  4. Android实现两次按下返回键退出
  5. Android与Js交互获取返回值
  6. Android三种实现定时器的方法
  7. Android(安卓)Service 之 Bound Services
  8. Android实现模拟点击的一种方法
  9. 浅谈Java中Collections.sort对List排序的两种方法

随机推荐

  1. Android(安卓)编译之android.mk
  2. Android(安卓)VideoView简单播放视频
  3. 世界范围内浏览器市场份额调查,symbian不
  4. Android(安卓)基础UI编程4
  5. android 从sdcard 读取图片 剪切 粘贴
  6. Android控件布局属性大全
  7. 第五次Android课堂笔记
  8. 使用GitHub Actions实现Android自动打包a
  9. Android(安卓)获取前台应用
  10. Android(安卓)Textview控件