Android 代码中实现返回键功能

代码里实现返回键

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

  • 采用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);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值