6

I am trying to invoke my main activity's onKeyDown() with KEYCODE_BACK, so that it behaves as if I pressed the 'back' button myself. I do that using the following code:

   KeyEvent goBackDown = new KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_BACK,0,0);
    goBackDown.dispatch(activity);
    SystemClock.sleep(50);  // as if human pressed the key
    KeyEvent goBackUp = new KeyEvent(0,0,KeyEvent.ACTION_UP,KeyEvent.KEYCODE_BACK,0,0);
    goBackUp.dispatch(activity);

My activity's onKeyDown() currently only calls:

return super.onKeyDown(keyCode, event);

Yet, unlike the real Back button, when the "fake" code is called, the activity refuses to become invisible.

Why?

srf
  • 2,410
  • 4
  • 28
  • 41

3 Answers3

12

use

dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_BACK));

http://developer.android.com/reference/android/view/View.html#dispatchKeyEvent%28android.view.KeyEvent%29

Aleadam
  • 40,203
  • 9
  • 86
  • 108
  • @srf `public final boolean dispatch (KeyEvent.Callback receiver)` is deprecated. `public final boolean dispatch (KeyEvent.Callback receiver, KeyEvent.DispatcherState state, Object target)` should in theory work also, but I have no experience using it. – Aleadam Apr 22 '11 at 04:12
  • @Aleadam Could we create KeyEvent object using unicode char value? – smartkid Oct 30 '15 at 13:46
3

Aleadam method don't work on my android 4.1.2. So I write workaround:

public void dispachBackKey() {
    dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
    dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
}
neworld
  • 7,757
  • 3
  • 39
  • 61
2

Try using this

public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
        //....
    }
    return true;
}
droid kid
  • 7,569
  • 2
  • 32
  • 37
  • Thanks but I am already doing this. When I wrote "my onKeyDown() currently only calls super" I was merely simplifying the description. I actually Log.v() to LogCat in onKeyDown() to verify that my "fake" event is actually being called. It is, but when it reaches the point of having to become invisible, it doesn't. – srf Apr 22 '11 at 02:05