Android: callback function from java script in java

I created an application in which I use webview and load a simple static html page. I am calling a java script function from an action, but I cannot call a function from a java script. I tried a little link, but that did not work.
Javascript callback function goes into Android
I can't call android function from javascript
Here is my code. Thank you in advance.


acitivity_main.xml

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Call JavaScript Function"
        android:onClick="callJavaScript" />

<WebView
    android:id="@+id/myWebView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

index.html

<html>
<head>
<script type="text/javascript">
        function displayMessage(){
            document.getElementById('test1').innerHTML = 'This is from java script.';
            Android.returnResult();
        }
    </script>
</head>
<body>
    <h1 id="test1">Hello World</h1>
</body>
</html>

The main activity has the following two functions.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView) this.findViewById(R.id.myWebView);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.addJavascriptInterface(new JavaScriptHandler(this), "Android");
        myWebView.loadUrl("file:///android_asset/index.html");
    }

    public void callJavaScript(View view) {
        Log.v(null, "Calling java Script");
        myWebView.loadUrl("javascript:displayMessage()");
    }

This is the JavaScriptHandler class

public class JavaScriptHandler {
    Context mContext;

    public JavaScriptHandler(Context context) {
        mContext = context;
    }

    public void returnResult() {
        Log.v(null, "result received");
    }
}
+4
source share
1 answer

To do this

@JavascriptInterface
public void returnResult() {
    Log.v(null, "result received");
}

JavaScript JavaScript.

+4

All Articles