How to avoid the hardware back button to close a modal view in Android?

Hey Guys, do you know how to avoid in Android the hardware back button to close a modal view?

Thank you.

Right now, this is very closed off and not possible. We are working on opening up the APIs needed to make this possible though.

Ok, thank you @mhartington!

@Corin, do this in your modal component:
constructor(params: NavParams, platform:Platform, viewCtrl: ViewController) { // ... platform.registerBackButtonAction(() => { // Just left empty and the modal will not be dismissed // If need to dismiss, just do: viewCtrl.dismiss(); }); // ... }

Working in beta 10.

Well, this works for the modal but unfortunately the hardware back button isn’t working anywhere else in the app. Or did i get it wrong?

Maybe you’ll need to de-register the action someway. Probably in the function that is called to dismiss the modal.

Any solution right now?

This might be of use :slight_smile:

1 Like

Well, according to the API documentation for Platform service:

registerBackButtonAction(fn, priority)

Returns: Function
A function that, when called, will unregister the back button action.

So in your modal

public unregister: any;

constructor (...){
 this.unregister=platform.registerBackButtonAction( () => {...});
...
}

And when you are ready to return the hardware back button to its default behavior:

this.unregister();
1 Like

Helpful . it is closing overlay but it is not closing model .Please check once .

ViewController is not working in app.component.ts . now what to do ? should i write that backbutton code in other file ?

Doesn’t work because the ViewController object that is passed to constructor of app.components is different from that you expect.

Like I said in my response, the function must be declared in the Modal component to viewCtrl.dissmis() work as you expect.

The Platform.registerBackButtonAction() works like a stacker. The last function registered is the first to be called.

Do not forget to unregister this same function when the component is destroyed.

Read this documentation entries for more information:
https://ionicframework.com/docs/api/platform/Platform/#registerBackButtonAction
https://ionicframework.com/docs/api/navigation/ViewController/#dismiss