您的位置:首页 > 移动开发 > Android开发

Android 代码中实现返回键功能

2015-12-11 11:58 771 查看

代码里实现返回键

刚才自己的项目里用到了

有两种办法:

采用
Runtime


[code]/**
 * 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
注意此方法不能再主线程中

[code]/**
* 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
,实现对返回键的监听

[code]@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //do something
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: