基于PhoneGap2.9框架的android插件的实现

PhoneGap平台提供了插件功能,开发者可以将重量级的功能封装在原生代码开发的插件中,并将接口暴露给JavaScript,JavaScript调用插件功能即可完成与本地代码的交互。开发一个简单的android插件主要分以下几步:

(1)编写JAVA类,继承CordovaPlugin类,如下:

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

public class Login extends CordovaPlugin {

public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
if (action.equals(“login”)) {
String message = args.getString(0);
this.login(message, callbackContext);
return true;
}
return false;
}

private void login(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(“loginSuccess”);
} else {
callbackContext.error(“Expected one non-empty string argument.”);
}
}

}

(2)在config.xml 里注册插件,如下:

 

<feature name=”Login”>
<param name=”android-package” value=”cn.com.vs.service.Login”/>
</feature>

(3)js调用,如下:

 

<script type=”text/javascript” charset=”utf-8″>
function login(str, callback) {
var exec = cordova.require(‘cordova/exec’);
exec(callback, function(err) {
callback(‘Nothing to echo.’);
}, “Login”, “login”, [str]);
};
function success (result) {
alert(“SUCCESS: \r\n”+result );
}
login(“para”, success);
</script>

(4)打印出loginSuccess,即可成功!

Tagged: ,

Comments are closed.