关于an-d-ro-id:Android与js互相调用

5次阅读

共计 2069 个字符,预计需要花费 6 分钟才能阅读完成。

Android 与 js 相互调用

有话要说

本篇次要总结了简略的 Androidjs相互调用的办法。

在开发过程中遇到了须要在安卓中调用 js 办法的需要,于是将具体的实现过程总结成这篇博客。

成果

其中“调用安卓办法”按钮是 html 中的按钮;“调用 JS 办法”按钮是 app 中的按钮。

本地 HTML

首先,在 app 根目录新建一个 assets 文件夹,并在文件夹内新建一个本地 html 文件,如下图

接着编写一个简略的 html 文件:

<html lang="zh-CN">
<p id='p'>hello world</p>

<script>
        function test(){document.getElementById("p").innerHTML += "你好!"
        }
</script>

<button onclick="justTest.hello('js 调用安卓办法!')"> 调用安卓办法 </button>

</html>

Android 布局文件

<?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="调用 js 办法" />

</LinearLayout>

安卓调用 js 办法

能够看到,在本地 html 中曾经有了一个test 函数,上面来在安卓中调用这个test 函数

加载本地 html 文件

webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/show.html");

定义按钮的点击事件

Button btn = findViewById(R.id.btn);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {testJS();
    }
});

其中 testJS 代码为:

@SuppressLint("SetJavaScriptEnabled")
public void testJS() {webView.loadUrl("javascript:test()");
}

据此,就实现了安卓调用 js 办法。

js 调用安卓办法

首先,须要在 activity 中定义被调用的办法:

@JavascriptInterface
public void hello(String msg) {Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();}

并且须要给 webview 绑定上 java 对象:

webView.addJavascriptInterface(this, "justTest");

最初,在 js 中调用该办法:

<button onclick="justTest.hello('js 调用安卓办法!')"> 调用安卓办法 </button>

这样就实现了在 js 中调用安卓办法。

总结

因为工作忙碌,好久没写博客了。

当前会抽出工夫多多总结本人在工作中所学习的内容的。

这篇博客写了一个很简略的一个 demo,然而安卓和js 相互调用在理论开发中很有用,顺便做一个总结。

相干教程

Android 根底系列教程:

Android 根底课程 U - 小结_哔哩哔哩_bilibili

Android 根底课程 UI- 布局_哔哩哔哩_bilibili

Android 根底课程 UI- 控件_哔哩哔哩_bilibili

Android 根底课程 UI- 动画_哔哩哔哩_bilibili

Android 根底课程 -activity 的应用_哔哩哔哩_bilibili

Android 根底课程 -Fragment 应用办法_哔哩哔哩_bilibili

Android 根底课程 - 热修复 / 热更新技术原理_哔哩哔哩_bilibili

本文转自 https://juejin.cn/post/6844903969727184904,如有侵权,请分割删除。

正文完
 0