Change Hardware Back Button


Hello everyone,
I want to change the hardware back button behavior depending on wich page of the app I’m using: I want to go back at the homepage for all the pages except for the homepage, where I want the back button that closes the app,

How can I do that?
Thanks for your support.