首页 > 代码库 > Crosswalk+Cordova开发安卓app之 JavaScript调用java (附源代码下载)

Crosswalk+Cordova开发安卓app之 JavaScript调用java (附源代码下载)

 Crosswalk+Cordova开发安卓app之 JavaScript调用java (附源代码下载)


  1. 定义js回调接口

    /**
    	 * js回调接口
    	 * 
    	 * @author graceup
    	 * 
    	 */
    	public class JsInterface {
    		public JsInterface() {
    		}
    
    		@JavascriptInterface
    		public String sayHello() {
    			// TODO do more thing
    			return "Hello World!";
    		}
    	}

           备注:这里的 @JavaScriptInterface 所在的包是 import org.xwalk.core.JavascriptInterface;

  2. XWalkView设置JavaScript可用且绑定对象     

    setContentView(R.layout.activity_main);
    		mXWalkView = (XWalkView) findViewById(R.id.activity_main);
    		
    		//绑定
    		mXWalkView.addJavascriptInterface(new JsInterface(), "NativeInterface");
    
    		mXWalkView.load("file:///android_asset/www/index.html", null);

  3. 调用html执行JavaScript或直接执行Javascript调用Java

    mXWalkView.load("file:///android_asset/www/index.html", null);

    index.html源码:

    <button onclick="clicked()">button</button>
    <script>
    function clicked() {
      alert(NativeInterface.sayHello());
    }
    </script>

下载地址:http://download.csdn.net/detail/graceup/8405123



Crosswalk+Cordova开发安卓app之 JavaScript调用java (附源代码下载)