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

2015-07-20 17:22:55 · 作者: · 浏览: 5

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

?

?

  1. 定义js回调接口

    ?

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

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

    ?

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

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

    ?

  3. 调用html执行java script或直接执行java script调用Java

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

    index.html源码

    
    <script>
    function clicked() {
      alert(NativeInterface.sayHello());
    }
    

    ?

    ?

    ?