如何在 android 网络视图中调用 javascript 中程序员定义的函数?

How do you call a programmer-defined function in javascript in an android webview?

我已经在 html 文件中放置了一个高位图仪表,并将其加载到网络视图中。我创建了一个名为 set_needle() 的函数,将指针设置为某个值。但是当我尝试在 Java 中加载对那个函数的 java 脚本调用时,没有任何反应。我看过几个例子,在我看来他们正在做我正在做的事情,所以我不确定问题是什么。

这是 html/js:

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>

<body>
<div id="container" style="min-width: 310px; max-width: 400px; height: 300px; margin: 0 auto"></div>

<script type="text/javascript">

var needle_value = 0;

function set_value(new_val) {
    needle_value = new_val;
    console.log("setting needle");
}

$(function () {

$('#container').highcharts({

    chart: {
        type: 'gauge',
        plotBackgroundColor: null,
        plotBackgroundImage: null,
        plotBorderWidth: 0,
        plotShadow: false
    },

    title: {
        text: 'Activity Index - Last 24 Hour'
    },

    pane: {
        startAngle: -125,
        endAngle: 125,
        background: [{
            backgroundColor: {
                linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
                stops: [
                    [0, '#FFF'],
                    [1, '#333']
                ]
            },
            borderWidth: 0,
            outerRadius: '109%'
        }, {
            backgroundColor: {
                linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
                stops: [
                    [0, '#333'],
                    [1, '#FFF']
                ]
            },
            borderWidth: 1,
            outerRadius: '107%'
        }, {
            // default background
        }, {
            backgroundColor: '#DDD',
            borderWidth: 0,
            outerRadius: '105%',
            innerRadius: '103%'
        }]
    },

    // the value axis
    yAxis: {
        min: 0,
        max: 200,

        minorTickInterval: 'auto',
        minorTickWidth: 1,
        minorTickLength: 0,
        minorTickPosition: 'inside',
        minorTickColor: '#666',

        tickPixelInterval: 40,
        tickWidth: 1,
        tickPosition: 'inside',
        tickLength: 14,
        tickColor: '#666',
        tickAmount: 11,

        labels: {
            step: 5,
            rotation: 'auto',
            format: '{value}%'
        },
        title: {
            text: 'Activity<br />Index',
            style: {'fontSize':'11px'},
            y: 5
        },
        plotBands: [{
            from: 0,
            to: 60,
            color: '#DF5353' // red
        }, {
            from: 60,
            to: 80,
            color: '#DDDF0D' // yellow
        }, {
            from: 80,
            to: 120,
            color: '#55BF3B' // green
        },
        {
            from: 120,
            to: 140,
            color: '#DDDF0D' // yellow
        },
        {
            from: 140,
            to: 200,
            color: '#DF5353' // red
        }]
    },
    credits: {
        enabled: false
    },
    exporting: {
        enabled: false
    },
    series: [{
        name: 'Activity Index',
        data: [20],
        tooltip: {
            valueSuffix: '% of daily average'
        }
    }]

},
// Add some life
function (chart) {
    if (!chart.renderer.forExport) {
        setInterval(function () {
            var point = chart.series[0].points[0];

            point.update(needle_value);

        }, 3000);
    }
});
});
</script>

这里是相关的 java 代码:

    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.setWebChromeClient(new WebChromeClient());
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);

    myWebView.loadUrl("file:///android_asset/SleepActivity.html");
    myWebView.loadUrl("javascript:set_value(50)");

这是一个示例界面:

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

像这样将它连接到 WebView:

webView.addJavascriptInterface(new WebAppInterface(this), "Android");

Android 是 javascript 对象的名称,因此您可以像这样从 javascript 调用它:

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
</script>

@JavascriptInterface 注释很重要;如果没有,则无法从 javascript.

调用该方法

由于您在 html 页面加载 url 指令之后立即调用了 JavaScript 函数,因此在尝试执行 JavaScript,导致错误。
如果是这种情况,我建议推迟对自定义 WebViewClient 的 onPageFinished 回调的 myWebView.loadUrl("javascript:set_value(50)"); 指令。类似于:

myWebView.setWebViewClient(new WebViewClient(){
    @Override
    public void onPageFinished(WebView view, String url) {
        view.loadUrl("javascript:set_value(50)");
    }
});