服务Q Q:75303307

网站优化

网站建设

工作时间:周一至周五:8:30-6:00 周六、日:9:00-5:00

技术点滴

您的位置:主页 > 新闻观点 > 技术点滴 > 详细内容>

Eclipse PhoneGap 构建 Android 应用程序快速入门

2012-12-04 22:16 作者:admin [ ]

 

首先,要明白一点,就是要利用PhoneGap框架开发移动应用时,也是必须在开发环境上安装对应移动设备应用的SDK的。

比如你要开发一个运行在Android上的应用,则必须安装 Android的SDK包,开发iphone应用,就要安装iphone sdk。

还要明白Cordova是PhoneGap贡献给Apache后的开源项目,是从PhoneGap中抽出的核心代码,是驱动PhoneGap的核心引擎。你可以把他想象成类似于Webkit和Google Chrome的关系。

本文将介绍如何安装基于Android SDK下安装PhoneGap,按下面的方法配置以后,你就可以用你熟悉的html+javascript的方式来进行原生android应用的开发了.

无论是开发基于哪种平台的移动应用,首先要到PhoneGap的官方网站下载

PhoneGap包,地址是:http://www.phonegap.com/download,目前最新的版本是0.9.1,下载之后,解压缩后,会发现如下图所示的若干个文件夹:这里,由于我们是构建Android应用,因此只有phonegap-android对我们是有用的。

由于PhoneGap是通过Ruby语言以及所开发的目标移动设备的SDK一起搭配工作的,因此除了下载PhoneGap外,开发者还必须安装如下的软件(以Android为例)

我的版本:

Android SDK,  android-sdk_r12-windows(最新的那个)

Eclipse IDE  eclipse-SDK-3.7-win32(这个也是最新的)


JDK   jdk-6u10-rc2-bin-b32-windows-i586-p-12_sep_2008(最新地)

Android 的Eclipse插件ADT(http://developer.android.com/sdk/eclipse-adt.html)(可省略,安装完之后可以直接下载android所有插件包)

phonegap

我只列出我实际操作中用到的软件,系统是windows。

Eclipse 以及 Android 的安装查看以下网页 http://www.apkbus.com/android-43332-1-1.html ,还算详细。

今天主要说以下phonegap的构建,因为我发现网上的一些教程出来的效果都是错误的,可能是版本问题。

有英文基础的查看http://www.phonegap.com/start#android

英文不好的看下面。

首先进入eclipse界面,新建android工程 new > android project

14f8f5560fb30f249e67ebb5c895d143ac4b037b.jpg

 

然后在该工程目录下建立两个文档

/libs 和 /assets/www

把之前下载好的phonegap中的phonegap.js拷贝到 /assets/www下

phonegap.jar拷贝到/libs下(一般会带版本号,自己改下文件名)

下面是被大家忽略的一步(网上大部分教程少了这步)

复制phonegap下的xml文件夹到 /res下

接下来是修改工程的一些文件,修改src文件下的java文件

把class extent 的activity改成DroidGap

Replace the setContentView() line with super.loadUrl("file:///android_asset/www/index.html");

Add import com.phonegap.*;

Removeimport android.app.Activity;(国内很多教程也没有这步,虽然不会报错,但是会出现感叹号,举手之劳删了吧)

605529a0d933c8950ef29fcdd11373f083020074.jpg

 

接下来你可能会看见边框出现一些红色叉叉,没事。

只是因为eclipse没有找到phonegap.jar而已,帮他找到就好了。

右击 libs文件夹 进去Build Paths/ > Configure Build Paths

java Build Path > Libraries  单击Add JARs(似乎和AddExternal JARs没啥差别)

找到libs下的phonegap.jar路径,单击ok。再按F5刷新下就可以了。

接下来打开 总目录下的AndroidManifest.xml文件 右击 Open With > Text Editor

在版本号下面添加下面这段代码


<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:resizeable="true"
android:anyDensity="true"
/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" />

添加 android:configChanges="orientation|keyboardHidden"进去activity的属性里面

把第二段代码添加进入第一个activity标签的后面

<activity android:name="com.phonegap.DroidGap" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden"> <intent-filter> </intent-filter> </activity>

如图:

97adba07baa1cd11c84a7596b912c8fcc2ce2d04.jpg

 

最后,在assets/www下创建一个index.html文件

代码如下:


<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>

</html>


保存,右击工程run as ->Android Application

 

以下这个index.html是有比较全测试phonegap(cordova)功能的文件

 

<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/index.css" />
        <title>Hello World</title>
    </head>
    <body>
         <div id="info" > 
       <h4>Platform: <span id="platform" > &nbsp;</span>,
       Version: <span id="version" >&nbsp;</span></h4> 
       <h4>UUID: <span id="uuid" > &nbsp;</span>, 
       Name: <span id="name" >&nbsp;</span></h4> 
       <h4>Width: <span id="width" > &nbsp;</span>,
       Height: <span id="height" >&nbsp; 
       </span>, Color Depth: <span id="colorDepth" ></span></h4> 
    </div>    
   <a href="#" class="btn large" onclick="get_contacts();">
   Get phone's contacts</a>
   <div id="conlist" > 
   </div>  
        <script type="text/javascript" src="cordova-2.2.0.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
        
        <script type="text/javascript" charset="utf-8" > 
//这一段注释掉的是演示获取设备信息及获取通讯录
        /*
 //show device information 
 var deviceInfo = function (){      
     document.getElementById("platform").innerHTML = device.platform; 
     document.getElementById("version").innerHTML = device.version; 
     document.getElementById("uuid").innerHTML = device.uuid; 
     document.getElementById("name").innerHTML = device.name; 
     document.getElementById("width").innerHTML = screen.width; 
     document.getElementById("height").innerHTML = screen.height; 
     document.getElementById("colorDepth").innerHTML = screen.colorDepth; 
    }; 
      //listen the device ready event and get the device information. 
 function init(){ 
document.addEventListener("deviceready", deviceInfo, true ); 
  } 

 // get device contacts list by the contacts API. 
 function get_contacts() 
  { 
var obj = new ContactFindOptions(); 
obj.filter=""; 
obj.multiple=true ; 
obj.limit=5; 
navigator.service.contacts.find(["name","displayName", "phoneNumbers", 
"emails"],contacts_success, fail, obj); 
  } 

function fail(fail) 
    { 
      alert(fail); 
    } 
function contacts_success(contacts) 
 { 
var result = ""; 
for (var i=0;i<contacts.length;i++) 
   { 
result += "Name: " + contacts[i].name.givenName + ", displayName: "+ 
contacts[i].displayName + ",Email:" + contacts[i].emails[0].value; 
result += "<br>"; 
   } 
document.getElementById("conlist").innerHTML = result; 
alert(contacts.length + ' contacts returned.' ); 
  } 
  */
 </script>  
        
        <script type="text/javascript" charset="utf-8">
    //这一段是获取网络连接信息 更多方法可以参考api,此文件可以更容易理解phonegap怎么用 http://docs.phonegap.com/en/2.2.0/index.html
    // Wait for Cordova to load
    // 
    document.addEventListener("deviceready", onDeviceReady, false);

    // Cordova is loaded and it is now safe to make calls Cordova methods
    //
    function onDeviceReady() {
        checkConnection();
    }

    function checkConnection() {
        var networkState = navigator.connection.type;

        var states = {};
        states[Connection.UNKNOWN]  = 'Unknown connection';
        states[Connection.ETHERNET] = 'Ethernet connection';
        states[Connection.WIFI]     = 'WiFi connection';
        states[Connection.CELL_2G]  = 'Cell 2G connection';
        states[Connection.CELL_3G]  = 'Cell 3G connection';
        states[Connection.CELL_4G]  = 'Cell 4G connection';
        states[Connection.NONE]     = 'No network connection';

        alert('Connection type: ' + states[networkState]);
    }

    </script>
        <script type="text/javascript" charset="utf-8">
//这一段注释的是对设备文件系统进行操作
/*
    // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Cordova is ready
    //
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
    }

    function gotFS(fileSystem) {
        fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
    }

    function gotFileEntry(fileEntry) {
        fileEntry.createWriter(gotFileWriter, fail);
    }

    function gotFileWriter(writer) {
        writer.onwriteend = function(evt) {
            console.log("contents of file now 'some sample text'");
            writer.truncate(11);  
            writer.onwriteend = function(evt) {
                console.log("contents of file now 'some sample'");
                writer.seek(4);
                writer.write(" different text");
                writer.onwriteend = function(evt){
                    console.log("contents of file now 'some different text'");
                }
            };
        };
        writer.write("some sample text");
    }

    function fail(error) {
        console.log(error.code);
    }
*/
    </script>
    </body>
</html>