Poking around the forum I ran across this:
-- main.lua -- require the composer library local composer = require "composer" composer.gotoScene( "scene1" ) -- Key listener local platformName = system.getInfo( "platformName" ) local function onKeyEvent( event ) if ( platformName == "Android" ) then if event.phase == "down" then if event.keyName == "back" then local currScene = composer.getSceneName( "current" ) local prevScene = composer.getSceneName( "previous" ) if currScene == "firstScene" then -- present an alert asking if the user wants to quit the app. elseif prevScene then composer.gotoScene( prevScene ) end return true end end end end Runtime:addEventListener( "key", onKeyEvent )
When I started playing with it I noticed a couple things.
1. system.getInfo( "platformName" ) has been deprecated. Use "platform" instead.
2. On my simulator no matter what I do, this command always returns win32. So I can't test this code.
Do we really need the platform check? Apple isn't going to send us these keys anyway right?
3. On my android phone, the back key isn't processed unless it is released. So this code should check for "up" instead of "down".
4. It would be slightly more efficient to check for "up" after the check for "back". This code is processing any keyboard key that is pushed down, not just the back button.
local function onKeyEvent( event ) if ( event.keyName == "back" ) then if event.phase == "up" then -- released back key exitpage() end return true -- true indicates to android that the app is taking over back function end return false -- Let android process this key normally. end