phonegap-plugin

说白就是使用js调用java代码,蛮有意思的,不难看出phonegap的很多类库都是使用plugin的模式做的。

index.html
<!DOCTYPE html>
<html>
<head>
<title>Storage Example</title>

<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
	// Wait for Cordova to load
	//
	document.addEventListener("deviceready", onDeviceReady, false);

	// Cordova is ready
	//
	function onDeviceReady() {
		PhoneGap.exec(successFunction, failFunction, "MyPlugin","echo",["a","b"]);
	}
	
	function successFunction(e){
		alert("success:"+e);
	}
	function failFunction(e){
		alert("fail:"+e);
	}

</script>
</head>
<body>
	<h1>Example</h1>
	Plugin



</body>
</html>


res/xml/config.xml *这部需要注意一下,不要忘记配置
 <plugin name="MyPlugin" value="com.fanfq.phonegap.plugin.MyPlugin"/>


src/com/fanfq/phonegap/plugin/MyPlugin.java
package com.fanfq.phonegap.plugin;

import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyPlugin extends Plugin {

    /**
     * Executes the request and returns PluginResult.
     *
     * @param action        The action to execute.
     * @param args          JSONArry of arguments for the plugin.
     * @param callbackId    The callback id used when calling back into JavaScript.
     * @return              A PluginResult object with a status and message.
     */
    public PluginResult execute(String action, JSONArray args, String callbackId) {
        try {
            if (action.equals("echo")) {
                String echo = args.getString(0); 
                if (echo != null && echo.length() > 0) { 
                    return new PluginResult(PluginResult.Status.OK, "hello fanfq!");
                } else {
                    return new PluginResult(PluginResult.Status.ERROR);
                }
            } else {
                return new PluginResult(PluginResult.Status.INVALID_ACTION);
            }
        } catch (JSONException e) {
            return new PluginResult(PluginResult.Status.JSON_EXCEPTION,"error");
        }
    }
    

}


附件中含完整工程,问题请留言。

猜你喜欢

转载自fanfq.iteye.com/blog/1684633
今日推荐