Android WebView 踩坑之路
摘要:
H5定位
// 定位(location)
settings.setGeolocationEnabled(true);
String dir = this.getApplicationContext().getDir("database"...
H5定位
// 定位(location) settings.setGeolocationEnabled(true); String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); //設定定位的資料庫路徑 settings.setGeolocationDatabasePath(dir); webView.setWebChromeClient(new WebChromeClient() { @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } // 處理javascript中的alert public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { return true; } // 處理javascript中的confirm public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { return true; } @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); super.onGeolocationPermissionsShowPrompt(origin, callback); } });
Http、Https混雜圖片無法載入
WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); settings.setLoadWithOverviewMode(true); settings.setBlockNetworkImage(false); settings.setAppCacheEnabled(true);// 預設值 false settings.setLoadsImagesAutomatically(true); // 是否自動載入圖片 // 儲存(storage) settings.setDomStorageEnabled(true);// 預設值 false settings.setDatabaseEnabled(true); settings.setCacheMode(WebSettings.LOAD_DEFAULT); @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { //super.onReceivedSslError(view, handler, error); // handler.proceed();// 接受所有網站證書 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } }
微信、支付寶、打電話無法調起
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url == null) return false; if (url.startsWith("tel:")) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } try { if (url.startsWith("weixin://") || url.startsWith("alipays://") || url.startsWith("mailto://") || url.startsWith("tel://") //其他自定義的scheme ) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } } catch (Exception e) { //防止crash (如果手機上沒有安裝處理某個scheme開頭的url的APP, 會導致crash) return false; } view.loadUrl(url); return true; }