Method Example for Interaction between Android and Vue

  • 2021-09-11 21:12:09
  • OfStack

Anyone who has done Android mixed development should know how to interact between Java code and Javascript code in Android.

First, review the interaction between Java and Javascript under 1.

JavaScript calls Java

WebView in Android adds the Java method for the Html page to call:


mWebView.addJavascriptInterface(new DirectToJS(), "AndroidObj");

class DirectToJS{
  @JavascriptInterface
  public void showToast(){
    Toast.makeText(this, "Android Toast",Toast.LENGTH_SHORT).show();
  }
}

On the Html page, JavaScript calls the Java method as follows:


window.AndroidObj.showToast();

In JavaScript code: window is the Window entity of the web page, which is very familiar to people who do front-end development; AndroidObj is an entity provided by Android to WebView, and Android will assign this entity to window of WebView; showToast () is the method that Java provides to Html.

Java calls JavaScript

First, write a common JavaScript method on Html:


function showAlert(){
  alert("Html Alert");
}

In Android, you only need to execute the following code:


mWebView.loadUrl("javascript:showAlert()");

Pits on Vue Frame

If the front end uses the Vue framework, if you write a method directly on the js script, Android cannot be called, no matter where it is written.

This is because in the Vue framework, the method on the script is not a method belonging to window, so you should assign the method provided to Android to window, so that it can be called in Android:


window['showAlert'] = {
  alert("Html Alert");
}

Generally speaking, for ordinary web pages, the methods written on js scripts belong to window entities by default; In the Vue framework, because the implementation mechanism within the framework is special, the method you write on the js script is not the method on the real page, so it cannot be called in Android.


Related articles: