将变量从Android Activity传递给JavaScript

时间:2014-05-09 04:46:53

标签: javascript android

假设我有两个变量x和y,我想将它们从MyActivity传递给JavaScript。这是我的代码:

public class myNewActivity extends Activity {
    double x;
    double y;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new);

        // get extras passed from another activity
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            x = extras.getDouble("x");
            y = extras.getDouble("y");
        }

        WebView webView = (WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        //webView.loadUrl("javascript:setX('"+x+"')");
        //webView.loadUrl("javascript:setY('"+y+"')");
        webView.loadUrl("file:///android_asset/index.html");    
    }

我正在尝试使用这两条注释的行,但只是崩溃了应用程序。这是JavaScript:

var x, y;
    function init(){
        // ... here I need the values of X and Y

    }
    function setX(ex) {
        x = ex;
    }
    function setY(ey) {
        y = ey
    }

1 个答案:

答案 0 :(得分:2)

你需要像这样在webview中实现javascriptinteface;

WebView webView = (WebView) findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());

    Bundle extras = getIntent().getExtras();
    double x = 0, y = 0;
    if (extras != null) {
        x = extras.getDouble("x");
        y = extras.getDouble("y");
    }
    webView.addJavascriptInterface(new JavaScriptInterface(x, y), "JSInterface");
    webView.loadUrl("file:///android_asset/index.html");

在您的活动中创建此Javainteface

public class JavaScriptInterface {

        double x, y;

        JavaScriptInterface(double x, double y) {
            this.x = x;
            this.y = y;
        }

        public double getXValue() {
            return x;
        }

        public double getYValue() {
            return y;

        }
    }

在index.html中

var x, y;
    function init(){
       x = JSInterface.getXValue();
       y = JSInterface.getYValue();
    }