在Android WebView中反对@JavascriptInterface?

时间:2017-09-04 11:18:10

标签: javascript java android webview

我知道如何在Java代码中调用JavaScrip方法。它由@JavascriptInterface注释完成。但是,如果我想通过Android确定应该调用来自 JS方法呢?我在JS中使用提到的注释调用Android Dialog,其中我有switch语句,它应该确定应该在JS中调用哪个函数。我使用了一个无法正常工作的标志,因为Dialogs没有同步,所以方法showDialog()在Dialog启动之前完成。有没有办法在对面达成Android-JS通信?

@JavascriptInterface
public int showDialog(){
    new AlertDialog.Builder(this.activity)
            .setTitle("Share iamge as...")
            .setItems(new CharSequence[]{"Image", "PDF document", "Print"}, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which){ // this switch should determine which JS function I call
                        case 0: chosenMethod = 0; // here should be called JS function (eg. exportImage() from JS code)
                            Log.v("Dialog onClick()", "method chosen" + chosenMethod);
                            break;
                        case 1: chosenMethod = 1;
                            Log.v("Dialog onClick()", "method chosen" + chosenMethod);
                            break;
                        case 2: chosenMethod = 2;
                            Log.v("Dialog onClick()", "method chosen" + chosenMethod);
                            break;
                    }
                }
            })
            .create().show();
    Log.v("Dialog out of onClick", "method chosen" + chosenMethod);
    return chosenMethod;
}

1 个答案:

答案 0 :(得分:1)

你可以做到

macro_rules! timer {
    ($( $x: expr ),+ ) => {
        let now = SystemTime::now();
        let val = $x;

        match now.elapsed() {
            Ok(elapsed) => {
                // This should include a message at some point alongside the timing
                println!("{}", elapsed.as_secs());
            }
            Err(e) => {
                println!("{:?}", e);
            }
        }
        val
    } 
}

在网页视图中加载网页后,任何时候运行JS功能。

如果它不起作用:检查您的webview设置(security / js)。