webview做跳转app的逻辑

Webview是Android系统中用于将网页嵌入到应用程序中的控件。在移动应用中,有时需要跳转到应用的某个页面或执行某个操作,这时就可以使用Webview的跳转功能。

Webview跳转app的原理如下:

1. 通过JS交互通信

Webview可以通过JavaScript桥接(WebView.addJavascriptInterface(Object object, String name)方法)与页面中的JavaScript进行通信,这样就可以将被跳转的APP的信息通过JavaScript在Webview中传递。同时需要在Webview中重写shouldOverrideUrlLoading方法,可以在这个方法中实现跳转逻辑,对检测到的原生协议做处理,如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实现跳转

URL Scheme是iOS和Android平台都支持的APP间相互跳转的协议,可以在应用程序中定义 URL Scheme,在需要调用 APP 的地方通过调用这些定义好的 URL Scheme 来触发 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页面的协作下实现。通过在WebView中嵌入具有相应业务逻辑的HTML5应用,用户可以在原有 WebView 业务的基础上,通过一定的操作使应用跳转到其他原生应用程 序中进行业务处理。