Android Back Button is DUPLICATING

Hello, I have made an app showing the Corona SDK Documentation using a webView. There is one little problem though, and it is a bit strange, when I implemented the Android’s physical back button to have the webView go back one step in history, it is not doing that, it is doing it twice. I can’t seem to figure this out, help would be appreciated!

-- Called when a key event has been received. local function onKeyEvent( event ) -- Print which key was pressed down/up to the log. local message = "Key '" .. event.keyName .. "' was pressed " .. event.phase print( message ) -- If the "back" key was pressed on Android, then prevent it from backing out of your app. if (event.keyName == "back") and (system.getInfo("platformName") == "Android") then webView:back() return true end -- Return false to indicate that this app is \*not\* overriding the received key. -- This lets the operating system execute its default handling of this key. return false end -- Add the key event listener. Runtime:addEventListener( "key", onKeyEvent );

If you would like to see this issue for yourself you can get the app on Google Play by CLICKING HERE

This is because a key has 2 phases.  A “down” phase and an “up” phase.  Your code is telling the webview to navigate back on both the “down” and the “up” phase.  You should change your code to only navigate back on the “down” phase in your if condition like this…

if (system.getInfo("platformName") == "Android") then if (event.keyName == "back") and (event.phase == "down") then webView:back() return true end end

Thank you so much for the FAST and INFORMATIVE reply. Worked like a charm. By the way that code was pulled from Corona’s documentation itself, maybe we should inform them to update the code to your fixed one.

1 Like

Right, but that example was preventing the “back” key from backing out of the app, which I suppose in that case it’s better to return true for both phases just to be safe.  You do bring up a good point though.

1 Like

This is because a key has 2 phases.  A “down” phase and an “up” phase.  Your code is telling the webview to navigate back on both the “down” and the “up” phase.  You should change your code to only navigate back on the “down” phase in your if condition like this…

if (system.getInfo("platformName") == "Android") then if (event.keyName == "back") and (event.phase == "down") then webView:back() return true end end

Thank you so much for the FAST and INFORMATIVE reply. Worked like a charm. By the way that code was pulled from Corona’s documentation itself, maybe we should inform them to update the code to your fixed one.

Right, but that example was preventing the “back” key from backing out of the app, which I suppose in that case it’s better to return true for both phases just to be safe.  You do bring up a good point though.