WebView是一个基于WebKit引擎、展现Web页面的控件。Android的WebView在低版本和高版本采用了不同的WebKit版本内核,Android4.4后使用的是Chrome内核。
目录
1、WebView的常见方法
2、WebSettings类:对WebView进行配置和管理
3、WebViewClient类:处理各种通知 & 请求事件
4、WebChromeClient类:
5、如何避免WebView内存泄露
6、webView中文件下载
7、往webview注入js
8、Cookie管理
9、Android5.0上 WebView中Http和Https混合问题
10、文件上传、图片选择
11、H5 video全屏播放
12、webview缓存
状态:
导航:
缓存:
//声明WebSettings子类
WebSettings webSettings = webView.getSettings();
设置自适应屏幕,两者合用
缩放操作
//其他细节操作
辅助 WebView 处理 Javascript 的对话框,网站图标,网站标题等
返回false,则仍旧执行alert || confirm || prompt
返回true,则代表接管浏览器的弹框,可以由安卓自定义行为,如果是confirm、prompt则需要对JsResult进行调用,从而通知浏览器Android这边的处理结果。
onGeolocationPermissionsShowPrompt(String origin,GeolocationPermissions.Callback callback) //通知主程序web内容尝试使用定位API,但是没有相关的权限。主程序需要调用调用指定的定位权限申请的回调
onGeolocationPermissionsHidePrompt() // 通知程序有定位权限请求。如果onGeolocationPermissionsShowPrompt权限申请操作被取消,则隐藏相关的UI界面
onShowFileChooser(WebView webView, ValueCallback filePathCallback,FileChooserParams fileChooserParams) // 通知客户端显示文件选择器。用来处理file类型的HTML标签,响应用户点击选择文件的按钮操作。调用filePathCallback.onReceiveValue(null)并返回true取消请求操作。
建议不要在xml布局文件中定义WebView控件,而是在需要的时候在Activity中直接创建,并且Context上下文推荐使用getApplicationContext.
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
// 获取WebView实例
webView = new WebView(getApplicationContext());
webView.setLayoutParams(params);
mLayout.addView(webView);
在Activity销毁(WebView)时,先让WebView加载null内容,然后移除WebView,再销毁WebView,最后把WebView设置为null
@Override
protected void onDestroy() {
// 避免WebView内存泄露
if (webView != null) {
webView.loadDataWithBaseURL(null, "", "text/html", "UTF-8", null);
webView.clearHistory();
((ViewGroup) webView.getParent()).removeView(webView);
webView.destroy();
webView = null;
}
super.onDestroy();
}
/** * 当下载文件时打开系统自带的浏览器进行下载,当然也可以对捕获到的 url 进行处理在应用内下载。 **/
webView.setDownloadListener(new FileDownLoadListener());
private class FileDownLoadListener implements DownloadListener {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppBridge(new WebAppBridge.OauthLoginImpl() {
@Override
public void getWebAuth(String result) {
Toast.makeText(getApplicationContext(), "js通过webView调用原生方法", Toast.LENGTH_LONG).show();
webView.post(new Runnable() {
@Override
public void run() {
// android主动调用web js方法
String username = "bird001";
String channel = "android";
webView.loadUrl("javascript:androidWebModule.logout('" + username + "','" + channel + "')");
}
});
}
}), "webAndroidModule");
public class WebAppBridge {
private OauthLoginImpl oauthLogin;
public interface OauthLoginImpl {
void getWebAuth(String result);
}
public WebAppBridge(OauthLoginImpl login) {
this.oauthLogin = login;
}
// 必须添加此注解
@JavascriptInterface
public void getAuth(String str) {
if (this.oauthLogin != null) {
oauthLogin.getWebAuth(str);
}
}
}
/**
* 将cookie设置到 WebView
* @param url 要加载的 url
* @param cookie 要同步的 cookie
*/
public static void syncCookie (String url, String cookie){
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.createInstance(context);
}
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true); /** * cookie 设置形式 * cookieManager.setCookie(url, "key=value;" + "domain=[your domain];path=/;") **/
cookieManager.setCookie(url, cookie);
}
/**
* 移除cookie
* 这个两个在 API level 21 被抛弃
* CookieManager.getInstance().removeSessionCookie();
* CookieManager.getInstance().removeAllCookie();
* 推荐使用这两个, level 21 新加的
* CookieManager.getInstance().removeSessionCookies();
* CookieManager.getInstance().removeAllCookies();
**/
public static void removeCookies () {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.flush();
} else {
CookieSyncManager.createInstance(Application.getInstance());
CookieSyncManager.getInstance().sync();
}
}
/**
* MIXED_CONTENT_ALWAYS_ALLOW:允许从任何来源加载内容,即使起源是不安全的;
* MIXED_CONTENT_NEVER_ALLOW:不允许Https加载Http的内容,即不允许从安全的起源去加载一个不安全的资源;
* MIXED_CONTENT_COMPATIBILITY_MODE:当涉及到混合式内容时,WebView 会尝试去兼容最新Web浏览器的风格。
**/if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
H5代码:
// Android 5.0以下版本的文件选择回调
protected ValueCallback mValueCallbackLow;
// Android 5.0及以上版本的文件选择回调
protected ValueCallback mValueCallbackHigh;
// requestCode
protected static final int REQUEST_CODE_FILE_PICKER = 51426;
// 自定义WebChromeClient
private class OpenFileChromeClient extends WebChromeClient {
// Android 5.0以下版本选择文件时会触发,该方法为隐藏方法
public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
showFileChooser(uploadMsg, null, false);
}
// Android 5.0 (API level 21)以上版本会触发该方法,该方法为公开方法
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final boolean allowMultiple = fileChooserParams.getMode() == FileChooserParams.MODE_OPEN_MULTIPLE;//是否支持多选
showFileChooser(null, filePathCallback, true);
}
return true;
}
}
webView.setWebChromeClient(new OpenFileChromeClient());
/**
* 打开选择图片/相机
*/
private void showFileChooser(final ValueCallback low, final ValueCallback high, final boolean allowMultiple) {
//Android 5.0以下版本
if (mValueCallbackLow != null) {
mValueCallbackLow.onReceiveValue(null);
}
mValueCallbackLow = low;
//Android 5.0及以上版本
if (mValueCallbackHigh != null) {
mValueCallbackHigh.onReceiveValue(null);
}
mValueCallbackHigh = high;
// 相册&&文件
Intent intentPic = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// intentPic.setType(mUploadFileTypes); // 设置类型,不设置就会只打开相册
intentPic.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, allowMultiple);
// 拍照
Intent iPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mCameraFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + System.currentTimeMillis() + ".png";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// android7.0注意uri的获取方式改变
Uri photoOutputUri = FileProvider.getUriForFile(
getApplicationContext(),
BuildConfig.APPLICATION_ID + ".fileProvider",
new File(mCameraFilePath));
iPhoto.putExtra(MediaStore.EXTRA_OUTPUT, photoOutputUri);
} else {
iPhoto.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
}
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
// ACTION_CHOOSER标题
chooser.putExtra(Intent.EXTRA_TITLE, "文件上传");
// 选项
chooser.putExtra(Intent.EXTRA_INTENT, intentPic);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{iPhoto});
startActivityForResult(chooser, REQUEST_CODE_FILE_PICKER);
}
// 文件选择回调
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_CODE_FILE_PICKER && resultCode == RESULT_OK) {
if (intent == null) {
// 看是否从相机返回
File cameraFile = new File(mCameraFilePath);
if (cameraFile.exists()) {
Uri uri = Uri.fromFile(cameraFile);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
responseWeb(new Uri[]{uri});
Log.d(TAG, "onActivityResult: 相机返回" + (mValueCallbackHigh == null));
return;
}
} else {
Uri singleUri = intent.getData();
if (mValueCallbackLow != null) {
// 5.0以下版本
mValueCallbackLow.onReceiveValue(singleUri == null ? null : singleUri);
mValueCallbackLow = null;
Log.d(TAG, "onActivityResult: 低版本返回处理");
} else if (mValueCallbackHigh != null) {
// 5.0以上版本
if (singleUri != null) {
// 单选
mValueCallbackHigh.onReceiveValue(new Uri[]{singleUri});
mValueCallbackHigh = null;
Log.d(TAG, "onActivityResult: 高版本返回处理----》单选");
} else {
// 多选
final int count = intent.getClipData().getItemCount();
Uri[] uris = new Uri[count];
for (int i = 0; i < count; i++) {
uris[i] = intent.getClipData().getItemAt(i).getUri();
}
mValueCallbackHigh.onReceiveValue(uris);
mValueCallbackHigh = null;
Log.d(TAG, "onActivityResult: 高版本返回处理----》多选");
}
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
cancelFilePick();
}
}
/**
* 返回操作
* @param uris
*/
public void responseWeb(Uri[] uris) {
if (mValueCallbackHigh != null) {
mValueCallbackHigh.onReceiveValue(uris);
mValueCallbackHigh = null;
} else if (mValueCallbackLow != null) {
mValueCallbackLow.onReceiveValue(uris[0]);
mValueCallbackLow = null;
}
}
/**
* 取消操作
*/
public void cancelFilePick() {
//WebView对象,在用户取消文件选择器的情况下,需给onReceiveValue传null返回值
// 否则WebView在未收到返回值的情况下,无法进行任何操作,文件选择器会失效
if (mValueCallbackLow != null) {
mValueCallbackLow.onReceiveValue(null);
mValueCallbackLow = null;
} else if (mValueCallbackHigh != null) {
mValueCallbackHigh.onReceiveValue(null);
mValueCallbackHigh = null;
}
}
核心思路:h5播放器点击全屏播放会触发onShowCustomView,取消全屏播放会触发onHideCustomView。
全屏时,使用一个FrameLayout将之前的webView覆盖掉。取消全屏则将FrameLayout隐藏而重新webView。并且需要在切换屏幕方向时隐藏——显示titleBar
private void fullScreen() {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Log.i(TAG, "横屏");
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Log.i(TAG, "竖屏");
}
}
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
if (view instanceof FrameLayout && fullScreenView != null) { // A video wants to be shown
this.videoViewContainer = (FrameLayout) view;
this.videoViewCallback = callback;
fullScreenView.addView(videoViewContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
fullScreenView.setVisibility(View.VISIBLE);
isVideoFullscreen = true;
}
}
@Override
public void onHideCustomView() {
if (isVideoFullscreen && fullScreenView != null) { // Hide the video view, remove it, and show the non-video view
fullScreenView.setVisibility(View.INVISIBLE);
fullScreenView.removeView(videoViewContainer);
// Call back (only in API level <19, because in API level 19+ with chromium webview it crashes)
if (videoViewCallback != null && !videoViewCallback.getClass().getName().contains(".chromium.")) {
videoViewCallback.onCustomViewHidden();
}
isVideoFullscreen = false;
videoViewContainer = null;
videoViewCallback = null;
}
}