android 代码实现back键功能
方案一,简单但响应慢:
doExec("input keyevent 4"); public String doExec(String cmd) { String s = "/n"; try { Process p = Runtime.getRuntime().exec(cmd); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = in.readLine()) != null) { s += line + "/n"; } } catch (IOException e) { e.printStackTrace(); } return cmd; }
方案二,响应快:
public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: switch (v.getId()) { case R.id.bottom_nav_back: mDownTime = SystemClock.uptimeMillis(); sendEvent(KeyEvent.ACTION_DOWN, 0); break; break; case MotionEvent.ACTION_UP: switch (v.getId()) { case R.id.bottom_nav_back: case R.id.tv_back_dec: sendEvent(KeyEvent.ACTION_UP, 0); break; break; ... private void sendEvent(int action, int flags) { sendEvent(action, flags, SystemClock.uptimeMillis()); } private void sendEvent(int action, int flags, long when) { final int repeatCount = (flags & KeyEvent.FLAG_LONG_PRESS) != 0 ? 1 : 0; final KeyEvent ev = new KeyEvent(mDownTime, when, action, KeyEvent.KEYCODE_BACK, repeatCount, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags | KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY, InputDevice.SOURCE_KEYBOARD); InputManager.getInstance().injectInputEvent(ev, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC); }