Android and JS call each other
Have something to say
This article mainly summarizes the simple Android and JS mutual call method.
In the development process encountered the need to call JS method in Android requirements, so the specific implementation process summarized into this blog.
The effect
Where the “Call Android method” button is the HTML button; The “Call JS method” button is a button in the app.
Local HTML
First, create an Assets folder in the app root directory and create a local HTML file in the folder, as shown below
Then write a simple HTML file:
<html lang="zh-CN">
<p id='p'>hello world</p>
<script>
function test(){
document.getElementById("p").innerHTML += "Hello!
}
</script>
<button onclick="Justtest.hello ('js calls android method! ')">Calling android methods</button>
</html>
Copy the code
Android Layout file
<?xml version="1.0" encoding="utf-8"? >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<WebView
android:id="@+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call a js method" />
</LinearLayout>
Copy the code
Android calls the JS method
As you can see, you already have a test function in your native HTML. Let’s call the test function from Android.
Load the local HTML file
webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/show.html");
Copy the code
Define button click events
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { testJS(); }});Copy the code
The testJS code is:
@SuppressLint("SetJavaScriptEnabled")
public void testJS(a) {
webView.loadUrl("javascript:test()");
}
Copy the code
According to this, the implementation of Android call JS method.
Js calls the Android method
First, you need to define the method to be called in the activity:
@JavascriptInterface
public void hello(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
Copy the code
And we need to bind the WebView to a Java object:
webView.addJavascriptInterface(this."justTest");
Copy the code
Finally, call this method in js:
<button onclick="Justtest.hello ('js calls android method! ')">Calling android methods</button>
Copy the code
This allows you to call android methods in JS.
conclusion
I haven’t written blog for a long time due to my busy work.
Later will take out a lot of time to sum up their own learning in the work of the content.
This blog has written a very simple demo, but is android and JS call each other in the actual development is very useful, specifically to make a summary.