編輯:關於 Android 程式設計
從去年四月開始,專案裡就一直在用 JsBridge。之前寫過一篇入門介紹,這次繼續往深處走:在原有基礎上重新封裝一層,把重複程式碼收斂掉,讓上層呼叫變得更薄,快速搭出一個 Hybrid 應用。
動手之前先盤點一下商業 App 對 WebView 的常見訴求:
圍繞這些點,先把相關基礎知識鋪一遍。
WebView 是 Google 提供的系統元件,採用 WebKit 內核驅動,用來載入並渲染 HTML 頁面。最基礎的用法就是 loadUrl,線上地址與本地檔案都吃:
// 線上頁面
webView.loadUrl("https://www.baidu.com");
// 本地頁面
webView.loadUrl("file:///android_asset/demo.html");
WebViewClient 負責輔助 WebView 處理各類請求事件,常用的回呼有 onLoadResource、onPageStarted、onPageFinished、onReceivedError、onReceivedHttpAuthRequest、shouldOverrideUrlLoading 等。
本方案中的錯誤頁與公共 Header 注入都落在這裡。需要說明的是,Android 無法攔截 H5 自身發出的 ajax 請求,因此 Header 同步效果有限;建議 ajax 相關資料一律走 Cookie,避免服務端取不到 URL 上未附帶的參數。
附加 Header 的原生寫法是 loadUrl(url, header)。為了讓上層少寫樣板碼,可以把它收進 shouldOverrideUrlLoading:
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Map headers = this.onPageHeaders(url);
if (headers != null) {
view.loadUrl(url, headers);
}
return super.shouldOverrideUrlLoading(view, url);
}
錯誤頁則覆寫 onReceivedError,把失敗 URL 交給抽象方法決定回退到哪一頁:
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.loadUrl(this.onPageError(failingUrl));
}
onPageHeaders() 與 onPageError() 是拋給上層的兩個抽象口子。Activity 裡的用法就很直觀:
mProgressBarWebView.setWebViewClient(new CustomWebViewClient(mProgressBarWebView.getWebView()) {
@Override
public String onPageError(String url) {
return "file:///android_asset/error.html";
}
@Override
public Map onPageHeaders(String url) {
return CookieManager.getHeader(getContext());
}
});
WebChromeClient 負責處理 JS 對話框、網站圖示、頁面標題、載入進度等「瀏覽器裝飾」相關的事,常用回呼包括 onCloseWindow、onCreateWindow、onJsAlert、onJsPrompt、onJsConfirm、onProgressChanged、onReceivedIcon、onReceivedTitle、onShowCustomView。
如果只需要渲染 HTML,光有 WebViewClient 就夠了;一旦涉及 JS 互動、進度條、全螢幕播放等能力,就必須靠 WebChromeClient。這裡要的是頂部進度條,所以覆寫 onProgressChanged,順手也能拿到標題、實作全螢幕:
public class CustomWebChromeClient extends WebChromeClient {
private NumberProgressBar mProgressBar;
public CustomWebChromeClient(NumberProgressBar progressBar) {
this.mProgressBar = progressBar;
}
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress >= 95) {
this.mProgressBar.setVisibility(View.GONE);
} else {
if (this.mProgressBar.getVisibility() == View.GONE) {
this.mProgressBar.setVisibility(View.VISIBLE);
}
this.mProgressBar.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
}
}
這裡留 95% 的閾值有個實際原因:H5 的進度回報經常在後段停住,直接等 100 會讓進度條長時間掛在畫面上,不如提前收掉。
CookieManager 負責 Cookie 本身的增刪查改,提供 setAcceptCookie()、setCookie()、getCookie(url)、removeSessionCookies()、hasCookies()、removeAllCookie() 等 API。
CookieSyncManager 繼承自 WebSyncManager,負責把記憶體中的 Cookie 落盤,主要 API 有 resetSync()、stopSync()、sync()、syncFromRamToFlash()、checkInstanceIsAllowed()。
組合起來,注入並同步 Cookie 的程式碼大致如下:
CookieManager cookieManager = CookieManager.getInstance();
// 允許接受服務器下發的 cookie
cookieManager.setAcceptCookie(true);
// 清掉上一輪的 session cookie
cookieManager.removeSessionCookie();
// 注入自定義 cookie
List cookies = getCookies(customCookies);
for (String cookie : cookies) {
cookieManager.setCookie(uri.getHost(), cookie);
}
// 同步
CookieSyncManager.getInstance().sync();
要特別注意版本差異:5.0(LOLLIPOP)及以上,sync() 的路徑已改,必須改走 flush(),否則會出現「看起來同步了但實際沒落盤」的問題:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.flush();
} else {
CookieSyncManager.getInstance().sync();
}
如果想像 Header 那樣自定義一批 Cookie,格式是一個個 name=value 字串:
public static List createCustomCookies() {
List cookies = new ArrayList<>();
cookies.add("author=" + "tamic");
cookies.add("data=" + "2016.8.15");
cookies.add("key=" + "4fdfsfd34dfdfswer");
cookies.add("chanel=" + "簡書");
return cookies;
}
WebView 提供五種快取模式:
差異在弱網環境下特別明顯。以百度首頁為例,其 cache-control 為 no-cache,在 LOAD_DEFAULT 下無論如何都要走網路,斷網時直接落到錯誤頁;切到 LOAD_CACHE_ELSE_NETWORK 後,只要本地有快取就能正常呈現,僅在完全沒有快取時才回源。整體邏輯與 HTTP 快取一致,需要自定義快取時間與策略時可以從這裡下手。
清除快取:早期用 CacheManager.clearCache(true),但 4.4 之後該 API 已失效——快取清理涉及安全邊界,需要開發者自行實作,思路與 Picasso、OkHttp 自己管理磁碟快取相同。折中做法是直接呼叫 WebView.clearCache(true)。
清除歷史記錄:webView.clearHistory(),注意要放在 onPageFinished 之後呼叫,否則可能清不掉當前這一條。
基礎鋪墊完成後開始封裝。這裡直接擴展已有的 BridgeWebView,內部組合一個 BridgeWebView 與一個 NumberProgressBar,本質是一個 LinearLayout:
public class ProgressBarWebView extends LinearLayout {
static final String TAG = ProgressBarWebView.class.getSimpleName();
private NumberProgressBar mProgressBar;
private BridgeWebView mWebView;
public ProgressBarWebView(Context context) {
super(context);
this.init(context, null);
}
public ProgressBarWebView(Context context, AttributeSet attrs) {
super(context, attrs);
this.init(context, attrs);
}
@TargetApi(11)
public ProgressBarWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.init(context, attrs);
}
@TargetApi(21)
public ProgressBarWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
this.init(context, attrs);
}
}
為了讓回退鍵在網頁層生效,我在 init 裡屏蔽了長按(避免選 word 時彈菜單打斷操作),並攔截了返回鍵:
mWebView.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
return true;
}
});
this.mWebView.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK
&& ProgressBarWebView.this.mWebView.canGoBack()) {
ProgressBarWebView.this.mWebView.goBack();
return true;
}
return false;
}
});
另外別忘了內存洩漏:WebView 持有大量 Context 相關資源,Activity 銷毀時必須主動 destroy:
@Override
protected void onDestroyView() {
super.onDestroyView();
if (mProgressBarWebView.getWebView() != null) {
mProgressBarWebView.getWebView().destroy();
}
}
Native 約定給 JS 呼叫的介面(Java 側注册 handler):
public void registerHandler(final String handlerName, final JsHandler handler) {
this.mWebView.registerHandler(handlerName, new BridgeHandler() {
public void handler(String data, CallBackFunction function) {
if (handler != null) {
handler.OnHandler(handlerName, data, function);
}
}
});
}
Native 主動呼叫 JS:
public void callHandler(final String handlerName, String javaData, final JavaCallHandler handler) {
this.mWebView.callHandler(handlerName, javaData, new CallBackFunction() {
public void onCallBack(String data) {
if (handler != null) {
handler.OnHandler(handlerName, data);
}
}
});
}
可能有人會問 JsHandler 是哪來的——JsBridge 原始碼裡並沒有這個介面,它是為了讓上層呼叫更乾淨而自行加上的一層薄封裝:
public interface JsHandler {
void OnHandler(String handlerName, String data, CallBackFunction function);
}
初始化:
ProgressBarWebView mProgressBarWebView = (ProgressBarWebView) findViewById(R.id.login_progress_webview);
設置 WebViewClient:
mProgressBarWebView.setWebViewClient(new CustomWebViewClient(mProgressBarWebView.getWebView()) {
@Override
public String onPageError(String url) {
// 網路失敗時的兜底頁
return "file:///android_asset/error.html";
}
@Override
public Map onPageHeaders(String url) {
return null;
}
});
載入頁面:
mProgressBarWebView.loadUrl("file:///android_asset/demo.html");
// 也支援線上地址
宣告需要與 JS 約定的 handler:
ArrayList mHandlers = new ArrayList<>();
mHandlers.add("login");
mHandlers.add("callNative");
mHandlers.add("callJs");
mHandlers.add("open");
處理 JS 的呼叫:
mProgressBarWebView.registerHandlers(mHandlers, new JsHandler() {
@Override
public void OnHandler(String handlerName, String responseData, CallBackFunction function) {
if (handlerName.equals("login")) {
Toast.makeText(MainActivity.this, responseData, Toast.LENGTH_SHORT).show();
} else if (handlerName.equals("callNative")) {
Toast.makeText(MainActivity.this, responseData, Toast.LENGTH_SHORT).show();
function.onCallBack("我在上海");
} else if (handlerName.equals("callJs")) {
Toast.makeText(MainActivity.this, responseData, Toast.LENGTH_SHORT).show();
function.onCallBack("好的 這是圖片地址:xxxxxxx");
} else if (handlerName.equals("open")) {
mfunction = function;
pickFile();
}
}
});
注意 open 這個分支的處理方式:先跳出 WebView 去開系統相簿,等結果回來後再透過 mfunction.onCallBack(...) 把資料送回 H5。這類「Native 側需要等待非同步結果」的場景,正是把 CallBackFunction 引用暫存起來的典型用法。
Native 呼叫 JS:
mProgressBarWebView.callHandler("callNative", "hello H5, 我是 java", new JavaCallHandler() {
@Override
public void OnHandler(String handlerName, String jsResponseData) {
Toast.makeText(MainActivity.this, "h5返回的數據:" + jsResponseData, Toast.LENGTH_SHORT).show();
}
});
Native 單向推送訊息給 JS:
mProgressBarWebView.send("哈喽", new CallBackFunction() {
@Override
public void onCallBack(String data) {
Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
}
});
XML 佈局與 H5 側的 JS 程式碼這裡不再展開,可直接看專案中的範例。
GitHub:https://github.com/NeglectedByBoss/JsWebView ,覺得有幫助歡迎點個 star。
最後補一句實踐心得:這套封裝真正省下來的並不是行數,而是「每個頁面都要重寫一遍 Header、進度條、錯誤頁、返回鍵」的機械勞動。把這些橫切關注點收進一個自定義 View,業務頁面只需關心載入哪個 URL、約定哪些 handler,維護成本會明显下降。
透徹理解Android Service:基礎知識與編寫實戰
首先,什麼是Service? Service就是Android系統中的服務,它有這麼幾個特點:它無法與使用者直接交互,必須由使用者或其他程式顯式啟動;它的優先級比較高——
Android 四大組件之 Activity 全面解析
序言:Activity 作為 Android 四大組件之一,其重要性不言而喻。 本文目錄結構: Activity 是什麼 Activity 的創建 Activity 的
Android UI 元件:TabHost 標籤頁實作
Tab 標籤頁是 UI 設計中常見的元件,能讓使用者在多個分頁之間快速切換,每個分頁各自顯示不同內容。 TabHost 相當於瀏覽器中整排標籤頁的容器,而 TabSpe
仿電商 App 商品詳情頁:標題列隨滾動吸頂的懸浮效果
1、效果預覽 這個效果的用戶體驗確實相當酷炫,今天就來拆解它的實作方式。 2、先拆解結構 整個頁面可以分成四塊: • 懸浮內容 floatView