一、問題:在頂部或者底部反覆快速滑動界面,會出現自動向反方向滾動,或者視頻有聲音沒有畫面。 解決:在AndroidManifest.xml中給webview所在的activity添加硬體加速的屬性:android:hardwareAccelerated="true"。 說明:1、view控制項不能開啟 ...
一、問題:在頂部或者底部反覆快速滑動界面,會出現自動向反方向滾動,或者視頻有聲音沒有畫面。
解決:在AndroidManifest.xml中給webview所在的activity添加硬體加速的屬性:android:hardwareAccelerated="true"。
說明:1、view控制項不能開啟硬體加速(webView.setLayerType(View.LAYER_TYPE_HARDWARE,null);這個設置無效),但是view控制項可以關閉該view的硬體加速:webView.setLayerType(View.LAYER_TYPE_SOFTWARE,null);
2、setLayerType方法只有在api>11才有。
3、參考網址:https://blog.csdn.net/u010142437/article/details/70915694
二、webview的設置
WebSettings webSettings=webView.getSettings();
webSettings.setUseWideViewPort(true);//設置WebView是應該啟用對“viewport”HTML元標記的支持還是應該使用寬視口。true:支持<meta>標簽的viewport屬性
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
webSettings.setMediaPlaybackRequiresUserGesture(false);
}
webSettings.setBlockNetworkLoads(false);
webSettings.setAllowContentAccess(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webSettings.setJavaScriptEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
webSettings.setDomStorageEnabled(true);//設置是否啟用DOM存儲API。預設false。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
webSettings.setAllowUniversalAccessFromFileURLs(true);//可以解決有聲音沒圖像得問題。設置是否允許在文件方案URL上下文中運行的JavaScript訪問來自任何來源的內容。同上。
}
webSettings.setSupportZoom(true);
webSettings.setAllowFileAccess(true); //設置可以訪問文件
webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通過JS打開新視窗 webSettings.setLoadsImagesAutomatically(true); //支持自動載入webSettings.setPluginState(WebSettings.PluginState.ON);
說明:參考網址:https://blog.csdn.net/zhanwubus/article/details/80340025
三、webview長按下載圖片。
webview.setOnLongClickListener(new OnLongClickLIstener(){
@Override
public boolean onLongClick(View view) {
int clickType=webview.getHitTestResult().getType();
if (clickType==WebView.HitTestResult.IMAGE_TYPE||clickType==WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE){
Log.d("webveiw","圖片url="+wv.getHitTestResult().getExtra());
}
return false;
}
});
拓展:WebView.HitTestResult.EDIT_TEXT_TYPE:選中的文字類型;
WebView.HitTestResult.PHONE_TYPE:處理撥號;
WebView.HitTestResult.EMAIL_TYPE:處理Email;
WebView.HitTestResult.GEO_TYPE:地圖類型;
WebView.HitTestResult.SRC_ANCHOR_TYPE:超鏈接;
WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:帶有鏈接的圖片類型;
WebView.HitTestResult.IMAGE_TYPE:圖片類型;
WebView.HitTestResult.UNKNOWN_TYPE:未知類型。
private ValueCallback<Uri> mUploadMessage;
四、webview調用原生上傳圖片,視頻,文件等。
全局變數:
private String acceptTypesStr;
private ValueCallback<Uri[]> uploadMessageAboveL;
private static final int FILE_CAMERA_RESULT_CODE = 129;
private File fileUpFile;
第一步:
webview.setWebChromeClient(new WebChromeClient(){
// For Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
showImgSeclect();
}
// For Android > 4.1.1
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType, String capture) {
acceptTypesStr=acceptType;
mUploadMessage = uploadMsg;
Log.d("qtest",acceptTypesStr);
showImgSeclect();
}
// For Android > 5.0支持多張上傳
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView webView,
ValueCallback<Uri[]> uploadMsg,
WebChromeClient.FileChooserParams fileChooserParams) {
acceptTypesStr="";
for (String str:fileChooserParams.getAcceptTypes()){
acceptTypesStr+=(TextUtils.isEmpty(acceptTypesStr)?"":";")+str;
}
Log.d("qtest",acceptTypesStr);
uploadMessageAboveL = uploadMsg;
showImgSeclect();
return true;
}
});
第二步:
/**
* 顯示相機和相冊選擇
*/
public void showImgSeclect() {
//註意申請許可權:Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE
if (TextUtils.isEmpty(acceptTypesStr))return;
Intent captureIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (acceptTypesStr.contains("image")){
captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUpFile=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()
+File.separator+"LinAn"+File.separator+"linan-"+System.currentTimeMillis()+".jpg");
}else if (acceptTypesStr.contains("video")){
captureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUpFile=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()
+File.separator+"LinAn"+File.separator+"linan-"+System.currentTimeMillis()+".mp4");
}
Uri mUri = null;
if (!fileUpFile.getParentFile().exists()) {
fileUpFile.getParentFile().mkdirs();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// 臨時允許
captureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mUri = FileProvider.getUriForFile(getContext(), getPackageName() + ".fileprovider", fileUpFile);
} else {
mUri = Uri.fromFile(fileUpFile);
}
//需要顯示應用的意圖列表,這個list的順序和選擇菜單上的圖標順序是相關的,請註意。
List<Intent> cameraIntents = new ArrayList<Intent>();
PackageManager packageManager = getContext().getPackageManager();
//獲取手機里所有註冊相機接收意圖的應用程式,放到意圖列表裡(無他相機,美顏相機等第三方相機)
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
String packageName = res.activityInfo.packageName;
Intent i = new Intent(captureIntent);
i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
i.setPackage(packageName);
i.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
cameraIntents.add(i);
}
//相冊選擇器
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(acceptTypesStr.contains("video")?"video/*":acceptTypesStr);
//intent選擇器
Intent chooserIntent = Intent.createChooser(i, "choose");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
((CommonWeexActivity)getContext()).startActivityForResult(chooserIntent, FILE_CAMERA_RESULT_CODE);
}
第三步:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
UMShareAPI.get(getContext()).onActivityResult(requestCode, resultCode, data);//qq和新浪的回調
if (null == mUploadMessage && null == uploadMessageAboveL) {
return;
}
//沒有返回值時的處理
if (resultCode != RESULT_OK) {
//需要回調onReceiveValue方法防止下次無法響應js方法
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(null);
uploadMessageAboveL = null;
}
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
}
return;
}
Uri result = null;
if (requestCode == FILE_CAMERA_RESULT_CODE) {
if (null != data && null != data.getData()) {
result = data.getData();
}
if (result == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// 臨時允許
result = FileProvider.getUriForFile(getContext(), getPackageName() + ".fileprovider", fileUpFile);
} else {
result = Uri.fromFile(fileUpFile);
}
}
//5.0以上設備的數據處理
if (uploadMessageAboveL != null) {
uploadMessageAboveL.onReceiveValue(new Uri[]{result});
uploadMessageAboveL = null;
} else if (mUploadMessage != null) {
//5.0以下設備的數據處理
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
}
五、webview中的video標簽,視頻全屏處理。
fl_video_full是該界面佈局文件中的占滿佈局的一個FrameLayout控制項。
ll_webview是該界面佈局文件中占滿佈局,包含webview。
getHostView().setWebChromeClient(new WebChromeClient(){
@Override
public void onHideCustomView() {
try {
if (webview.fl_video_full==null)return;
webview.ll_webview.setVisibility(View.VISIBLE);
webview.fl_video_full.setVisibility(View.GONE);
webview.fl_video_full.removeAllViews();
webview.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);webview.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}catch (Exception e){
Log.d("qtest",e.toString());
}
super.onHideCustomView();
}
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
try{
videoFull=view;
webview.ll_webview.setVisibility(View.GONE);
webview.fl_video_full.setVisibility(View.VISIBLE);
webview.fl_video_full.addView(videoFull);
webview.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
webview.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); }catch (Exception e){
Log.d("qtest",e.toString());
}
super.onShowCustomView(view, callback);
}
});
六、銷毀webveiw
if (webveiw!= null) {
webveiw.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
webveiw.clearHistory();
((ViewGroup)webveiw.getParent()).removeView(wv);
webveiw.destroy();
webveiw= null;
}
七、問題:webview載入https鏈接會出現空白頁。
解決方法:
WebViewClient webViewClient = new WebViewClient() {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// super.onReceivedSslError(view, handler, error);
try {
handler.proceed();
}catch (Exception e){}
}
};
說明:ssl證書過期的話,更新證書需要註意除了伺服器端,可能還需要更新DNS,即要更新好每個節點。