Please, anyone suggest, how can I disable back button press event while working with PhoneGap
?
I need to do something in my Activity
, (DroidGap
code) for controlling the back button event.
Even, the following code works well in my Activity
, but not working when being used with DroidGap
.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event);
}
In Android we can change the default behaviour of the any activity like keypress, back button press, swap left swap right, to do Disable Back Press we need to override default functionality of onBackPressed() or onKeyDown() method in Activity class.
Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity: // Disable onBack click requireActivity(). onBackPressedDispatcher. addCallback(this) { // With blank your fragment BackPressed will be disabled. }
Navigate to Android > Restrictions > Basic and click on Configure. Under Allow Device Functionality, you'll have the options to disable Home/Power button. Home Button-Uncheck this option to restrict users from using the Home Button. Power Off-Uncheck this option to restrict users from turning their devices off.
Calling setOnKeyListener
on appView
helped me out.
I just had to make a minor change in my above code snippet, which is as follows:
appView.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return onKeyDown(keyCode, event);
}
});
EDITED
There actually occurs two actions while key-pressing event - Action Up
& Action Down
So, the following should be used in order to get the key event.
appView.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
// Do Here whatever you want
return true;
}
return onKeyDown(keyCode, event);
}
});
Slightly better than Narendra's version. It can handle key up calls for key presses other than back button properly. Put the code below inside onCreate override for example.
appView.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
// Do Stuff Here
return true;
}
return onKeyUp(keyCode, event);
}
return onKeyDown(keyCode, event);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With