PhoneGap(Cordova)之js调用本地native的方法 2
来源:互联网 发布:选装修公司 知乎 编辑:程序博客网 时间:2024/05/22 17:50
一、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 false;
}
}
--------------------------------------------------------------------
三、注册插件,在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="读取账号信息" onclick="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文件,页面加载部分该类继承了CordovaInterface:
package com.liu;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.DroidGap;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.CordovaPlugin;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity implements CordovaInterface {
private CordovaWebView appView;
private final ExecutorService threadPool =Executors.newCachedThreadPool();
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
appView = (CordovaWebView) findViewById(R.id.appView);
Config.init(this);
appView.loadUrl("file:///android_asset/www/accountInfo.html", 4000);
// super.setIntegerProperty("splashscreen", R.drawable.ic_launcher);
// super.loadUrl("file:///android_asset/www/accountInfo.html", 4000);
}
@Override
public Activity getActivity() {
// TODO Auto-generated method stub
return this;
}
@Override
public ExecutorService getThreadPool() {
// TODO Auto-generated method stub
return threadPool;
}
@Override
public Object onMessage(String arg0, Object arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public void setActivityResultCallback(CordovaPlugin arg0) {
// TODO Auto-generated method stub
}
@Override
public void startActivityForResult(CordovaPlugin arg0, Intent arg1, int arg2) {
super.startActivityForResult(arg1, arg2);
}
}
------------------------------------------------------------------------
七、配置文件main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<org.apache.cordova.CordovaWebView
android:id="@+id/appView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
- PhoneGap(Cordova)之js调用本地native的方法
- PhoneGap(Cordova)之js调用本地native的方法 2
- PhoneGap(Cordova) :js调用native(2) ------Android篇
- cordova调用本地SQLite数据库的方法
- React Native:JS调用Android本地方法
- Cordova(PhoneGap)通过plugins调用Android Native并回调
- Cordova 3.x 基础(11) -- JS是如何调用本地API的?
- cordova工程webview注入本地js库的方法
- js通过cordova调用本地代码
- Phonegap通过JS访问本地接口的两种方法
- phonegap js 和 本地代码 调用原理
- Java native 本地方法调用
- 2PhoneGap与Cordova的关系?
- XX程序媛学习笔记--Cordova(PhoneGap)通过plugins调用Android Native并回调
- phonegap(Cordova) 入门教程
- phonegap(cordova)移动支付宝接口调用
- phoneGap开发IOS,JS调用IOS方法/phoneGap插件开发
- js调用本地QQ的方法
- Linux内核启动过程分析
- 在android中如何实现在应用首页按两次返回键(back)退出应用
- 十七周 被墨水污染的数字
- Linux引导过程内幕
- 双系统如何正确的删除Ubuntu
- PhoneGap(Cordova)之js调用本地native的方法 2
- 基于梯度调整的矩不变自动阈值图像分割算法
- Linux初始RAM磁盘介绍
- iOS中使用blend改变图片颜色
- 反射
- hive中的order by+sort by+distribute by+cluster by
- 关于json的一些误解
- UML建模工具Trufun Plato的下载及安装为Eclipse的插件
- jqGrid方法