PhoneGap - 后退按钮上的android退出

问题描述:

我正在尝试使用 jquery mobile 和cordova 对RSS 阅读器进行编程.我的 RSS 阅读器由 3 个页面组成(在同一个 HTML 文档中:page1、page2、page3).我正在尝试覆盖(硬件)后退按钮行为,以便它退出程序.为了检查我在项目设置中没有犯任何错误,我使用了 PhoneGap 示例项目并将其加载到 Eclipse 中.每个示例函数都有效,所以我已将 index.html 和 res 文件夹移至 phonegap 示例.在我的 index.html 中,我导入了以下脚本:

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>

我的 main.js 文件如下所示:

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);

您可以在第一个代码示例中检查我的脚本版本.关于如何让代码工作的任何想法,以便在我按下 Xperia Arc 上的后退按钮时它会简单地退出应用程序?如果需要,我可以上传我的完整代码.

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.

我已经在我的 android 手机上测试了 phonegap(cordova) 蜂鸣功能,它可以工作,所以这没有任何脚本执行不好的问题.它必须在 main.js 文件中.可能是 jquerymobile 后退按钮功能和 phonegap 后退按钮功能的兼容性问题.

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.

需要等待设备准备好添加事件监听器:

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);
}