Webview是Android系統(tǒng)中用于將網(wǎng)頁嵌入到應(yīng)用程序中的控件。在移動應(yīng)用中,有時需要跳轉(zhuǎn)到應(yīng)用的某個頁面或執(zhí)行某個操作,這時就可以使用Webview的跳轉(zhuǎn)功能。
Webview跳轉(zhuǎn)app的原理如下:
1. 通過JS交互通信
Webview可以通過JavaScript橋接(WebView.addJavascriptInterface(Object object, String name)方法)與頁面中的JavaScript進(jìn)行通信,這樣就可以將被跳轉(zhuǎn)的APP的信息通過JavaScript在Webview中傳遞。同時需要在Webview中重寫shouldOverrideUrlLoading方法,可以在這個方法中實(shí)現(xiàn)跳轉(zhuǎn)邏輯,對檢測到的原生協(xié)議做處理,如tel、mailto等,避免頁面被跳轉(zhuǎn)到其他應(yīng)用或?yàn)g覽器。代碼示例如下:
```
WebView webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSInterface(), “Android”);
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("app://")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
});
class JSInterface{
@JavascriptInterface
public void jumpToNative(String params){
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(params));
startActivity(intent);
}
}
```
2. 通過攔截URL Scheme實(shí)現(xiàn)跳轉(zhuǎn)
URL Scheme是iOS和Android平臺都支持的APP間相互跳轉(zhuǎn)的協(xié)議,可以在應(yīng)用程序中定義 URL Scheme,在需要調(diào)用 APP 的地方通過調(diào)用這些定義好的 URL Scheme 來觸發(fā) APP 的行為。同樣需要在Webview中重寫shouldOverrideUrlLoading方法,然后通過Intent啟動被跳轉(zhuǎn)APP。代碼示例如下:
```
WebView webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("app://")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
});
```
以上兩種方法都需要在App和H5頁面的協(xié)作下實(shí)現(xiàn)。通過在WebView中嵌入具有相應(yīng)業(yè)務(wù)邏輯的HTML5應(yīng)用,用戶可以在原有 WebView 業(yè)務(wù)的基礎(chǔ)上,通過一定的操作使應(yīng)用跳轉(zhuǎn)到其他原生應(yīng)用程 序中進(jìn)行業(yè)務(wù)處理。