PhoneGap(Cordova)之js调用本地native的方法

一、PhoneGap是跨平台的js调用本地native的插件,首先要在官网上下载版本,本文用的是2.9.0版本,

解压后将cordova-2.9.0.jar拷贝到libs下,将config.xml拷贝到res/xml下,将cordova.js拷贝到www下面,

详见下面的截图:

----------------------------------------------------------------------------------------------------------------

二、写插件Echo.java文件,必须CordovaPlugin接口 实现execute方法

package com.liu;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

public class Echo extends CordovaPlugin{  // 必须继承 CordovaPlugin
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        Log.e("-------------",action);
        Log.e("-------------",args.toString());
        if (action.equals("echo")) {
            callbackContext.success(" success");
            return true;
        }
        else {
   callbackContext.error(0);
  }
        return true;
    }
}

其中:

 

回调成功的函数callbackContext.success(" success");,相当于是调js中的,传递参数是‘success’

function(ci){
                    console.log(ci);
                    alert("sky.liu"+ci);
                    $('info').innerHTML = JSON.stringify(ci);
                   
              }

 

回调失败的函数callbackContext.error(0)

 

--------------------------------------------------------------------

三、注册插件,在config.xml文件中,注册是   

Echo是名字,com.liu.Echo具体位置

 <plugins>
        <plugin name="Echo" value="com.liu.Echo"/>
       
    </plugins>

--------

<?xml version="1.0" encoding="UTF-8"?>
<!--
 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.
-->
<widget xmlns     = "http://www.w3.org/ns/widgets"
        id        = "io.cordova.helloCordova"
        version   = "2.0.0">
    <name>Hello Cordova</name>

    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>

    <author href="http://cordova.io" email="dev@cordova.apache.org">
        Apache Cordova Team
    </author>

    <access origin="*"/>

    <!-- <content src="http://mysite.com/myapp.html" /> for external pages -->
    <content src="index.html" />

    <preference name="loglevel" value="DEBUG" />
    <!--
      <preference name="splashscreen" value="resourceName" />
      <preference name="backgroundColor" value="0xFFF" />
      <preference name="loadUrlTimeoutValue" value="20000" />
      <preference name="InAppBrowserStorageEnabled" value="true" />
      <preference name="disallowOverscroll" value="true" />
    -->

    <feature name="App">
      <param name="android-package" value="org.apache.cordova.App"/>
    </feature>
    <feature name="Geolocation">
      <param name="android-package" value="org.apache.cordova.GeoBroker"/>
    </feature>
    <feature name="Device">
      <param name="android-package" value="org.apache.cordova.Device"/>
    </feature>
    <feature name="Accelerometer">
      <param name="android-package" value="org.apache.cordova.AccelListener"/>
    </feature>
    <feature name="Compass">
      <param name="android-package" value="org.apache.cordova.CompassListener"/>
    </feature>
    <feature name="Media">
      <param name="android-package" value="org.apache.cordova.AudioHandler"/>
    </feature>
    <feature name="Camera">
      <param name="android-package" value="org.apache.cordova.CameraLauncher"/>
    </feature>
    <feature name="Contacts">
      <param name="android-package" value="org.apache.cordova.ContactManager"/>
    </feature>
    <feature name="File">
      <param name="android-package" value="org.apache.cordova.FileUtils"/>
    </feature>
    <feature name="NetworkStatus">
      <param name="android-package" value="org.apache.cordova.NetworkManager"/>
    </feature>
    <feature name="Notification">
      <param name="android-package" value="org.apache.cordova.Notification"/>
    </feature>
    <feature name="Storage">
      <param name="android-package" value="org.apache.cordova.Storage"/>
    </feature>
    <feature name="FileTransfer">
      <param name="android-package" value="org.apache.cordova.FileTransfer"/>
    </feature>
    <feature name="Capture">
      <param name="android-package" value="org.apache.cordova.Capture"/>
    </feature>
    <feature name="Battery">
      <param name="android-package" value="org.apache.cordova.BatteryListener"/>
    </feature>
    <feature name="SplashScreen">
      <param name="android-package" value="org.apache.cordova.SplashScreen"/>
    </feature>
    <feature name="Echo">
      <param name="android-package" value="org.apache.cordova.Echo"/>
    </feature>
    <feature name="Globalization">
      <param name="android-package" value="org.apache.cordova.Globalization"/>
    </feature>
    <feature name="InAppBrowser">
      <param name="android-package" value="org.apache.cordova.InAppBrowser"/>
    </feature>
    <!-- Deprecated plugins element. Remove in 3.0 -->
    <plugins>
        <plugin name="Echo" value="com.liu.Echo"/>
       
    </plugins>
</widget>
--------------------------------------------------------------------------------------------------------------------------------------

四、写js函数,在index.js中

 

window.NPhone = {
 makeCall: function(telNumber, callback) {
  cordova.exec(callback, function(err) {
         callback('Nothing to echo.');
     }, "Echo", "echo", ['111']);
 }
}

其中Echo是名字,echo是action,‘111’是参数,对应Echo.java中的execute方法的参数:String action, JSONArray args

其中callback, function(err) {
         callback('Nothing to echo.');
     },是调用成功时回调的方法callback,和调用失败时回调方法function(err);

-----------------------------------------------------------------------------------------------------------------------------

五、调用四中js的html文件是accountInfo.html文件

<!DOCTYPE html>
<html>
<head>
    <meta 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" />
    <title>Hello World</title>
    <style type="text/css" >body,div,p{font-size:28px;line-height:150%;}</style>
     <script type="text/javascript" src="index.js"></script>
      <script type="text/javascript" src="cordova.js"></script>
       <script type="text/javascript" src="index.js"></script>
</head>
<body>
    账号公司信息demo:
    <br />
    <input type="button" value="读取账号信息"  οnclick="getCompanyInfo();"/>
  
    <div id="info"></div>
  

    <script type="text/javascript">


            function getCompanyInfo(){
         
                window.NPhone.makeCall('111',function(ci){
                    console.log(ci);
                    alert("sky.liu"+ci);
                    $('info').innerHTML = JSON.stringify(ci);
                   
              });
            }
      //      function getCompanyInfo(){
       //   cordova.exec(function(ci){
       //             console.log(ci);
      //              $('info').innerHTML = JSON.stringify(ci);
        //       }, function(err) {
                
       //      }, "Echo", "echo", ['111']);

           // }

        
        </script>
</body>
</html>

其中:window.NPhone.makeCall就是调用并且参数与index.js中的参数对应,

------------------------------------------------------------------------------------------------

六、MainActivity.java文件,页面加载部分该类继承了DroidGap:

package com.liu;


import org.apache.cordova.DroidGap;

import android.os.Bundle;

import android.annotation.SuppressLint;

 

@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends DroidGap {


@Override
public void onCreate(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onCreate(savedInstanceState);
  super.onCreate(savedInstanceState);
 
          super.setIntegerProperty("splashscreen", R.drawable.ic_launcher);
 
          super.loadUrl("file:///android_asset/www/accountInfo.html", 4000);


}

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值