今天上海雷阵雨,在18楼看着窗外真是蛮壮观的,哈哈~~发现了一篇老外关于拓展phonegap的文章:
http://www.adobe.com/devnet/html5/articles/extending-phonegap-with-native-plugins-for-android.html
照着跑了一下,发现真是蛮神奇的,我们所要做的其实就几步(在配置好了phonegap开发环境的情况下)
1.首先在asset-》www文件下新建一个.js文件(叫HelloPlugin.js)
var HelloPlugin = {
callNativeFunction: function (success, fail, resultType) {
return cordova.exec( success, fail,
"com.tricedesigns.HelloPlugin",
"nativeAction", [resultType]);
}
};
2.新建一个本地的java class,类名为HelloPlugin,继承org.apache.cordova.api.Plugin,package名字为com.tricedesigns
3.copy下列代码进入到这个class
public class HelloPlugin extends Plugin {
public static final String NATIVE_ACTION_STRING="nativeAction";
public static final String SUCCESS_PARAMETER="success";
@Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
Log.d("HelloPlugin", "Hello, this is a native function called from PhoneGap/Cordova!");
//only perform the action if it is the one that should be invoked
if (NATIVE_ACTION_STRING.equals(action)) {
String resultType = null;
try {
resultType = data.getString(0);
}
catch (Exception ex) {
Log.d("HelloPlugin", ex.toString());
}
if (resultType.equals(SUCCESS_PARAMETER)) {
return new PluginResult(PluginResult.Status.OK, "Yay, Success!!!");
}
else {
return new PluginResult(PluginResult.Status.ERROR, "Oops, Error :(");
}
}
return null;
}
}
<script type="text/javascript" charset="utf-8" src="HelloPlugin.js"></script>
function callNativePlugin( returnSuccess ) {
HelloPlugin.callNativeFunction( nativePluginResultHandler, nativePluginErrorHandler, returnSuccess );
}
function nativePluginResultHandler (result) {
alert("SUCCESS: \r\n"+result );
}
function nativePluginErrorHandler (error) {
alert("ERROR: \r\n"+error );
}
<body οnlοad="onBodyLoad()">
<h1>Hey, it's Cordova!</h1>
<button οnclick="callNativePlugin('success');">Click to invoke the Native Plugin with an SUCCESS!</button>
<button οnclick="callNativePlugin('error');">Click to invoke the Native Plugin with an ERROR!</button>
</body>
7.在plugin.xml中添加下列标签
<plugin name="com.tricedesigns.HelloPlugin" value="com.tricedesigns.HelloPlugin"/>
8.运行即可,如果在logcat中发现以下文字hello,this is a native function.......表示拓展已经成功了。
项目代码可进我的qq群共享中拿(250395324)