Webview是Android系統(tǒng)中用于將網頁嵌入到應用程序中的控件。在移動應用中,有時需要跳轉到應用的某個頁面或執(zhí)行某個操作,這時就可以使用Webview的跳轉功能。
Webview跳轉app的原理如下:
1. 通過JS交互通信
Webview可以通過JavaScript橋接(WebView.addJavascriptInterface(Object object, String name)方法)與頁面中的JavaScript進行通信,這樣就可以將被跳轉的APP的信息通過JavaScript在Webview中傳遞。同時需要在Webview中重寫shouldOverrideUrlLoading方法,可以在這個方法中實現(xiàn)跳轉邏輯,對檢測到的原生協(xié)議做處理,如tel、mailto等,避免頁面被跳轉到其他應用或瀏覽器。代碼示例如下:
```
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實現(xiàn)跳轉
URL Scheme是iOS和Android平臺都支持的APP間相互跳轉的協(xié)議,可以在應用程序中定義 URL Scheme,在需要調用 APP 的地方通過調用這些定義好的 URL Scheme 來觸發(fā) APP 的行為。同樣需要在Webview中重寫shouldOverrideUrlLoading方法,然后通過Intent啟動被跳轉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é)作下實現(xiàn)。通過在WebView中嵌入具有相應業(yè)務邏輯的HTML5應用,用戶可以在原有 WebView 業(yè)務的基礎上,通過一定的操作使應用跳轉到其他原生應用程 序中進行業(yè)務處理。