1

I know how to call Java method in JavaScript code. It is done by @JavascriptInterface annotation. But what if I want to determine by Android which method from JS should be called? I'm calling an Android Dialog in JS using the mentioned annotation where I've got the switch statement which should determine which function should be called in JS. I used a flag which is not working because Dialogs are not synchronized so the method showDialog() is done before even Dialog starts. Is there any way to reach the Android-JS communication on the opposite side?

@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;
}
shurrok
  • 795
  • 2
  • 13
  • 43

1 Answers1

1

You can do

webView.loadUrl("javascript:doSomething()");

any time after a webpage was loaded in your webview, to run a JS function.

If it doesn't work: check your webview settings (security / js).

Frank
  • 12,010
  • 8
  • 61
  • 78
  • Should I pass my `WebView` to the method or there is another option to call `loadUrl` on it? – shurrok Sep 04 '17 at 12:02
  • You'd better open the dialog in your presenter/activity/fragment, and use a callback in the dialog, back to its creator. The callback implementation in the presenter/activity/fragment can do the JS call on the WebView. But this is actually another question. Good luck – Frank Sep 04 '17 at 12:09
  • It is working like a charm, but I got one problem when I call the function: `Uncaught ReferenceError: methodName is not defined ` – shurrok Sep 04 '17 at 12:15
  • Should **javascript** be instead name of the script from which I call method? – shurrok Sep 04 '17 at 12:16