1、首先说通过js打开第三方app的几种方式
function openApp() {
alert('testOpenApp');
//方式一:调用android上注册的js方法可以打开
//mobile.openPersonalBank("", "");
//方式二: iframe
// var ifr = document.createElement("iframe");
//ifr.src = "weixin://";
//ifr.style.display = "none";
// document.body.appendChild(ifr);
// window.setTimeout(function(){
// document.body.removeChild(ifr);
// alert("not install");
// },3000)
//方式三:window.location
var schemeUrl= "cmbmobilebank://cmbls/functionjump?action=gocorpno&corpno=001051&needlogin=false&loginmode=d&cmb_app_trans_parms_start=here&actgrpid=AGP201705101414577420003";
window.location.href =schemeUrl;
//方式四:window.open
window.open(schemeUrl, '_blank');
}
js调用android方法,需要在activity的webview注册js事件
mWebView.addJavascriptInterface(new JsInterface(this), "mobile");
@JavascriptInterface
public void openPersonalBank( String tranType,String payMode) {
callCMBApp();
}
private void callCMBApp()
{
final String url = "cmbmobilebank://CMBLS/FunctionJump?action=gofuncid&funcid=200015&serverid= CMBEUserPay&cmb_app_trans_parms_start=here&……";
try
{
Intent intent = new Intent();
Uri data = Uri.parse(url);
intent.setData(data);
intent.setAction("android.intent.action.VIEW");
startActivity(intent);
}
catch(Exception e)
{
Log.d("WebViewActivity", "Exception", e);
}
}
2、ERR_UNKNOWN_URL_SCHEME问题解决
以上几个方法在我的测试demo里面是可以的,但是集成到项目中就报错了ERR_UNKNOWN_URL_SCHEME,
后来通过排查原因是因为项目中的webview设置了setWebChromeClient,另外还多设置了一个
mWebView.setWebViewClient(new WebViewClient() {...});
而demo里面只设置了 wvTest.setWebChromeClient(new MyWebViewClient());,也许原因是只有WebChromeClient才支持通过js打开deeplink的app链接。
demo代码如下:
private void initView()
{
wvTest = (WebView) findViewById(R.id.wv_test);
wvTest.setWebChromeClient(new MyWebViewClient());
WebSettings webSettings = wvTest.getSettings();
//如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//允许js弹出窗口
//wvTest.loadUrl("file:///android_asset/html5/test_open_app.html");
wvTest.loadUrl("http://192.168.1.1:9080/mobilepay/mpdesk!pb.ac");
}
private class MyWebViewClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result)
{ AlertDialog.Builder b2 = new AlertDialog.Builder(MainActivity.this);
b2.setTitle(R.string.title).setMessage(message).setPositiveButton("ok",
new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
// MyWebView.this.finish();
}
});
b2.setCancelable(false);
b2.create();
b2.show();
return true;
}
}
3、扩展阅读:如何设置自己的APP能被第三方以js打开?
1)、配置intent-filter
android:host="figo"
android:pathPrefix="/test"/>
2)、js调用
function deeplinkTest()
{
var schemeUrl= "myandroid://figo/test";
window.location.href =schemeUrl;
}
myandroid 相当于https 是个schema
figo相当于blog.csdn.net 是个host
test相当于figo0423是个path