編輯:關於 Android 程式設計
WebView 與 JavaScript 的互動大致可涵蓋以下幾種組合:
1、本地 html 與本地 html 裡的 js 互動
2、本地 html 與本地 js 互動
3、網絡 html 與網絡 js 互動
4、網絡 html 與本地 js 互動
5、各情況下的動態添加 js
以上五點都能用同一套方式模擬。本篇以「本地 html 與本地 js 互動」(含動態添加 js)為例。
6、攔截 url 請求(在 webview 加載完成後觸發的請求 url)
7、攔截 url 請求後返回自己封裝的數據(基於第 6 點,加載完成後觸發一些請求數據的 url 時攔截並自行封裝數據返回給 webview)
註:第 6、7 點將在下一篇博客中介紹。
webview 能做什麼?以下引用自原作者 vanezkw:
1)webView 可以用 html 做介面排版,雖然目前用的人還不多,但當客戶端需要複雜的動態圖文混排時,它是個不錯的選擇。
2)直接顯示網頁,這也是它最基本的功能。
3)和 js 互動——如果你的 js 功底比 java 好,那用這種方式處理一些複雜邏輯會是個不錯的選擇。
註:此例為本地 html 引用本地 js。若想把 js 直接寫進 html,只需把 js.js 的程式碼複製到 html 對應的 <script></script> 標籤內即可。
首先在 assets 資料夾裡要有兩個檔案:.html 與 .js。

test.html:
<a href="https://www.baidu.com">js中調用本地方法</a> <script src="file:///android_asset/js.js"></script>
js.js:
function funFromjs(){ document.getElementById("mydiv").innerHTML="獲取id為mydiv的元素,並向其中添加文字!"; myObj.fun1FromAndroid("我的myObj回調"); }activity.xml:
<relativelayout android:layout_height="match_parent" android:layout_width="match_parent" tools:context="com.yanqy.yqy_jsexample.MainActivity" xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools"><button android:id="@+id/mButton" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="UI觸發webview中的js"> <webview android:id="@+id/mWebView" android:layout_below="@+id/mButton" android:layout_centerhorizontal="true" android:layout_height="wrap_content" android:layout_width="wrap_content"> </webview></button></relativelayout>
MainActivity.java:
package com.yanqy.yqy_jsexample; import android.content.Context; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private WebView mWebView; private Button mBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtn = (Button) findViewById(R.id.mButton); mWebView = (WebView) findViewById(R.id.mWebView); //設置編碼 mWebView.getSettings().setDefaultTextEncodingName("utf-8"); //支持js mWebView.getSettings().setJavaScriptEnabled(true); //設置背景顏色 透明 mWebView.setBackgroundColor(Color.argb(0, 0, 0, 0)); //設置本地調用對象及其接口 mWebView.addJavascriptInterface(new JavaScriptObject(this), "myObj"); //載入網頁 mWebView.loadUrl("file:///android_asset/test.html"); //點擊調用js中方法 mBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWebView.loadUrl("javascript:funFromjs()"); } }); } final class JavaScriptObject { private Context mContxt; public JavaScriptObject(Context mContxt) { this.mContxt = mContxt; } @JavascriptInterface //sdk17版本以上加上注解 public void funFromAndroid(String name) { //在此可以通過js返回數據name進行操作 Toast.makeText(mContxt, "調用funFromAndroid:" + name, Toast.LENGTH_LONG).show(); } } } 這裡的關鍵有三步:先在 Settings 裡開啟 setJavaScriptEnabled(true);再用 addJavascriptInterface 把一個本地物件以 myObj 之名注入到 WebView,讓 js 能反向呼叫 Java;最後 Java 端透過 loadUrl("javascript:...") 主動呼叫 js 函數。
同上,首先在 assets 資料夾裡要有 .html 與 .js 檔案。

test.html——這次把 <script></script> 標籤及其內容刪除:
js中調用本地方法
js.js(與第一點相同,不變):
function funFromjs(){ myObj.fun1FromAndroid("第一個js回調"); }MainActivity.java——需要讀取 js 並動態添加到 webview 中,才能達到「動態添加 js」的效果。先把 js 讀進一個 String:
//js文本 private String wholeJS = ""
//獲取js文本 InputStream mIs = null; try { mIs = getResources().getAssets().open("js.js"); if(mIs != null){ byte buff[] = new byte[1024]; ByteArrayOutputStream fromFile = new ByteArrayOutputStream(); FileOutputStream out = null; do { int numread = 0; numread = mIs.read(buff); if (numread <= 0) { break; } fromFile.write(buff, 0, numread); } while (true); wholeJS = fromFile.toString(); }else{ Toast.makeText(MainActivity.this, "js加載失敗", Toast.LENGTH_SHORT).show(); } } catch (IOException e) { e.printStackTrace(); }然後把讀到的 js 注入 webview:
mWebView.loadUrl("javascript:" + wholeJS);MainActivity 完整程式碼:
package com.yanqy.yqy_jsexample; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.widget.Button; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { private WebView mWebView; private Button mBtn; //js文本 private String wholeJS = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtn = (Button) findViewById(R.id.mButton); mWebView = (WebView) findViewById(R.id.mWebView); //設置編碼 mWebView.getSettings().setDefaultTextEncodingName("utf-8"); //支持js mWebView.getSettings().setJavaScriptEnabled(true); //設置背景顏色 透明 mWebView.setBackgroundColor(Color.argb(0, 0, 0, 0)); //設置本地調用對象及其接口 mWebView.addJavascriptInterface(new JavaScriptObject(this), "myObj"); //載入網頁 mWebView.loadUrl("file:///android_asset/test.html"); //點擊調用js中方法 mBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //觸發html中的js mWebView.loadUrl("javascript:funFromjs()"); } }); //獲取js文本 InputStream mIs = null; try { mIs = getResources().getAssets().open("js.js"); if(mIs != null){ byte buff[] = new byte[1024]; ByteArrayOutputStream fromFile = new ByteArrayOutputStream(); FileOutputStream out = null; do { int numread = 0; numread = mIs.read(buff); if (numread <= 0) { break; } fromFile.write(buff, 0, numread); } while (true); wholeJS = fromFile.toString(); }else{ Toast.makeText(MainActivity.this, "js加載失敗", Toast.LENGTH_SHORT).show(); } } catch (IOException e) { e.printStackTrace(); } //webview添加讀取的js mWebView.loadUrl("javascript:" + wholeJS); } final class JavaScriptObject { private Context mContxt; public JavaScriptObject(Context mContxt) { this.mContxt = mContxt; } @JavascriptInterface //sdk17版本以上加上注解 public void funFromAndroid(String name) { //在此可以通過js返回數據name進行操作 Toast.makeText(mContxt, "調用funFromAndroid:" + name, Toast.LENGTH_LONG).show(); } } } activity_main.xml 與第一點相同,不變。
第 6、7 點將在下一篇博客中介紹,內容關於攔截請求,以及 webview 一些常用的監聽事件。
自製 launch 命令:在 adb shell 中直接啟動指定 APK
為了調試方便,常常希望能直接知道 APK 的路徑就把它啟動起來,不必每次手打 am start -n 包名/類名。於是寫了這支命令。 使用方法 先把編出的檔案推到裝置:
Android 側滑菜單 DrawerLayout 的使用
現在側滑菜單的應用非常普遍,過去大多透過第三方庫 SlidingMenu 實現;如今也可以直接用官方提供的 DrawerLayout 完成。 一、建立抽屜布局 frag
Android 觸摸事件分發機制透視:View 篇
其實我一直想寫一篇關於 Android 事件分發機制的文章。從第一篇博客開始,我就在很多地方零散地用到了事件分發的知識,也有許多朋友問過我各種各樣的問題,比如:onTou
LayoutInflater 的 inflate:不同參數組合到底差在哪
LayoutInflater 有兩個以 XmlPullParser 為參數的重載: inflate(XmlPullParser parser, ViewGroup ro