Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

cordova - PhoneGap - android exit on backbutton

I am trying to program RSS reader using jquery mobile and cordova. My RSS reader consists of 3 pages (in same HTML document: page1, page2, page3). I am trying to override (hardware)backbutton behaviour so it would exit the program. To check that I am not doing any mistakes in project setup I have used PhoneGap example project and loaded it in Eclipse. Every sample function worked so I have moved my index.html and res folder to phonegap example. In my index.html I import the folowing scripts:

<script src="res/jquery-1.7.1.min.js"></script>
<script src="res/jquery.mobile-1.1.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8" src="main.js"></script>

and my main.js file look like this:

document.addEventListener("backbutton", function(e){
if($.mobile.activePage.is('#homepage')){
    e.preventDefault();
    navigator.app.exitApp();
}
else {
    navigator.app.backHistory()
}
}, false);

You can check version of my scripts in first code sample. Any ideas on how I could get the code working so it would simply exit app when I press backbutton on my Xperia Arc? I can upload my full code if needed.

EDIT: I have tested phonegap(cordova) beep function on my android phone and it works so this doesnt have anything with bad script implementation. It must be something in main.js file. Maybe some compatibility issue with jquerymobile backbutton functions and phonegap backbutton function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to wait for the device to be ready to add the event listener:

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady(){
    document.addEventListener("backbutton", function(e){
       if($.mobile.activePage.is('#homepage')){
           e.preventDefault();
           navigator.app.exitApp();
       }
       else {
           navigator.app.backHistory();
       }
    }, false);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...