Reputation: 2450
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?
Upvotes: 6
Views: 7802
Reputation: 7793
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));
}
Upvotes: 3
Reputation: 40391
use
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_BACK));
Upvotes: 12
Reputation: 7609
Try using this
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
//....
}
return true;
}
Upvotes: 2