Android與js互相調用


有話要說:

本篇主要總結了簡單的Android與js互相調用的方法。

在開發過程中遇到了需要在安卓中調用js方法的需求,於是將具體的實現過程總結成這篇博客。

效果:

其中“調用安卓方法”按鈕是html中的按鈕;“調用JS方法”按鈕是app中的按鈕。

本地HTML:

首先,在app根目錄新建一個assets文件夾,並在文件夾內新建一個本地html文件,如下圖

接着編寫一個簡單的html文件:

 1 <html lang="zh-CN">
 2 <p id='p'>hello world</p>
 3 
 4 <script>
 5         function test(){
 6             document.getElementById("p").innerHTML += " 你好!"
 7         }
 8 </script>
 9 
10 <button onclick="justTest.hello('js調用安卓方法!')">調用安卓方法</button>
11 
12 </html>

 

Android布局文件:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:orientation="vertical"
 7     tools:context=".MainActivity">
 8 
 9     <WebView
10         android:id="@+id/webview"
11         android:layout_width="wrap_content"
12         android:layout_height="wrap_content" />
13 
14     <Button
15         android:id="@+id/btn"
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:text="調用js方法" />
19 
20 </LinearLayout>

安卓調用js方法:

可以看到,在本地html中已經有了一個test函數,下面來在安卓中調用這個test函數。

加載本地html文件:

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

 

定義按鈕的點擊事件:

1 Button btn = findViewById(R.id.btn);
2 
3 btn.setOnClickListener(new View.OnClickListener() {
4     @Override
5     public void onClick(View v) {
6         testJS();
7     }
8 });

其中testJS代碼為:

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

據此,就實現了安卓調用js方法。

js調用安卓方法:

首先,需要在activity中定義被調用的方法:

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

並且需要給webview綁定上java對象:

1 webView.addJavascriptInterface(this, "justTest");

最后,在js中調用該方法:

1 <button onclick="justTest.hello('js調用安卓方法!')">調用安卓方法</button>

這樣就實現了在js中調用安卓方法。

總結:

由於工作繁忙,好久沒寫博客了。

以后會抽出時間多多總結自己在工作中所學習的內容的。

這篇博客寫了一個很簡單的一個demo,但是安卓和js互相調用在實際開發中很有用,特地做一個總結。

 

大家如果有什么疑問或者建議可以通過評論或者郵件的方式聯系我,歡迎大家的評論~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM