最近在開發過程中遇到一個問題,主要是調用第三方的實名認證,需要拍照和錄像;
辦過支付寶大寶卡和騰訊的大王卡的都知道這玩意,辦卡的時候就需要進行實名認證,人臉識別;
本來第三方平臺(xxx流量公司)說的是直接用WebView加載這個H5界面就完事了,我心想這麼簡單,那不是分分鐘的事,放着後面做(公司就我一個安卓,所以開發都是我說的算^_^,獨立開發有的時候還是挺爽);
結果到項目快要上線的時候,只想說一句mmp,根本調不了相機,這個時候怎麼搞,只有自己去實現了,才發現自己已經進了webview的深坑;
到處找資料,發現webview根本不能讓h5自己調用,ios是可以的,項目經理就說是我的鍋,真特麼又一句mmp(關鍵是這個H5還特麼不能改,不能提供給我調用的方法);
進入正題,首先來了解webview,這裏我分享兩篇大佬的博客
1,WebView開車指南
2,WebView詳解
看完這兩篇基本你已經可以隨意操作webview了, 但是,當你調用相機的時候你才發現這只是入坑的開始
第一個坑
調用相機之後,文件回調不了,其實根本就是沒有回調.這個時候你要去檢查你的webview的Settings了關鍵代碼,是否給足了權限;
WebSettings settings = webView.getSettings();
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setDomStorageEnabled(true);
settings.setDefaultTextEncodingName("UTF-8");
settings.setAllowContentAccess(true); // 是否可訪問Content Provider的資源,默認值 true
settings.setAllowFileAccess(true); // 是否可訪問本地文件,默認值 true
// 是否允許通過file url加載的Javascript讀取本地文件,默認值 false
settings.setAllowFileAccessFromFileURLs(false);
// 是否允許通過file url加載的Javascript讀取全部資源(包括文件,http,https),默認值 false
settings.setAllowUniversalAccessFromFileURLs(false);
//開啓JavaScript支持
settings.setJavaScriptEnabled(true);
// 支持縮放
settings.setSupportZoom(true);
其中settings.setDomStorageEnabled(true);
這個方法當時我沒加,血崩了一次;
第二個坑
WebChromeClient的openFileChooser()只調用了一次
- 1
- 2
首先了解爲什麼這個方法只調用了一次,看這篇博客就可
Android開發深入理解WebChromeClient之onShowFileChooser或openFileChooser使用說明
看了他基本你就瞭解怎麼回事了
第三個坑
怎麼區分是要調用相機是需要拍照還是錄視頻 這個時候你就要看WebViewClient的 shouldOverrideUrlLoading()方法了
,我是通過攔截url來判斷url裏面是拍照還是錄製視頻來加一個flag
這樣你調用你的相機的時候就可以分別處理了
第四個坑
android 7.0的FileProvider的坑
看洪陽大佬的這篇博客基本就瞭解了
Android 7.0 行爲變更 通過FileProvider在應用間共享文件吧
最後附上我自己的代碼吧
package com.sihaiwanlian.cmccnev.feature.verify.activitys;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.orhanobut.logger.Logger;
import com.sihaiwanlian.cmccnev.R;
import com.sihaiwanlian.cmccnev.utils.PhotoUtils;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class Certifica extends AppCompatActivity {
private final static String TAG = "villa";
@BindView(R.id.titleBar_iv_back)
ImageView mTitleBarIvBack;
@BindView(R.id.titleBar_btn_back)
Button mTitleBarBtnBack;
@BindView(R.id.titleBar_centerTV)
TextView mTitleBarCenterTV;
private WebView webView;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mUploadCallbackAboveL;
private final static int PHOTO_REQUEST = 100;
private final static int VIDEO_REQUEST = 120;
private final static String url = "your_url";
private boolean videoFlag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_certifica);
ButterKnife.bind(this);
initToolBar();
initWebView();
}
private void initToolBar() {
mTitleBarCenterTV.setText("實名認證");
}
//初始化webView
private void initWebView() {
//從佈局文件中擴展webView
webView = (WebView) this.findViewById(R.id.certifi_webview);
initWebViewSetting();
}
//初始化webViewSetting
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void initWebViewSetting() {
WebSettings settings = webView.getSettings();
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setDomStorageEnabled(true);
settings.setDefaultTextEncodingName("UTF-8");
settings.setAllowContentAccess(true); // 是否可訪問Content Provider的資源,默認值 true
settings.setAllowFileAccess(true); // 是否可訪問本地文件,默認值 true
// 是否允許通過file url加載的Javascript讀取本地文件,默認值 false
settings.setAllowFileAccessFromFileURLs(false);
// 是否允許通過file url加載的Javascript讀取全部資源(包括文件,http,https),默認值 false
settings.setAllowUniversalAccessFromFileURLs(false);
//開啓JavaScript支持
settings.setJavaScriptEnabled(true);
// 支持縮放
settings.setSupportZoom(true);
//輔助WebView設置處理關於頁面跳轉,頁面請求等操作
webView.setWebViewClient(new MyWebViewClient());
//輔助WebView處理圖片上傳操作
webView.setWebChromeClient(new MyChromeWebClient());
//加載地址
webView.loadUrl(url);
}
@OnClick(R.id.titleBar_btn_back)
public void onViewClicked() {
if (webView.canGoBack()) {
webView.goBack();// 返回前一個頁面
} else {
finish();
}
}
//自定義 WebViewClient 輔助WebView設置處理關於頁面跳轉,頁面請求等操作【處理tel協議和視頻通訊請求url的攔截轉發】
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Logger.e(url);
if (!TextUtils.isEmpty(url)) {
videoFlag = url.contains("vedio");
}
if (url.trim().startsWith("tel")) {//特殊情況tel,調用系統的撥號軟件撥號【<a href="tel:1111111111">1111111111</a>】
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else {
String port = url.substring(url.lastIndexOf(":") + 1, url.lastIndexOf("/"));//嘗試要攔截的視頻通訊url格式(808端口):【http://xxxx:808/?roomName】
if (port.equals("808")) {//特殊情況【若打開的鏈接是視頻通訊地址格式則調用系統瀏覽器打開】
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else {//其它非特殊情況全部放行
view.loadUrl(url);
}
}
return true;
}
}
private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
private Uri imageUri;
//自定義 WebChromeClient 輔助WebView處理圖片上傳操作【<input type=file> 文件上傳標籤】
public class MyChromeWebClient extends WebChromeClient {
// For Android 3.0-
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
Log.d(TAG, "openFileChoose(ValueCallback<Uri> uploadMsg)");
mUploadMessage = uploadMsg;
if (videoFlag) {
recordVideo();
} else {
takePhoto();
}
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
Log.d(TAG, "openFileChoose( ValueCallback uploadMsg, String acceptType )");
mUploadMessage = uploadMsg;
if (videoFlag) {
recordVideo();
} else {
takePhoto();
}
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Log.d(TAG, "openFileChoose(ValueCallback<Uri> uploadMsg, String acceptType, String capture)");
mUploadMessage = uploadMsg;
if (videoFlag) {
recordVideo();
} else {
takePhoto();
}
}
// For Android 5.0+
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
Log.d(TAG, "onShowFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)");
mUploadCallbackAboveL = filePathCallback;
if (videoFlag) {
recordVideo();
} else {
takePhoto();
}
return true;
}
}
/**
* 拍照
*/
private void takePhoto() {
imageUri = Uri.fromFile(fileUri);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
imageUri = FileProvider.getUriForFile(Certifica.this, getPackageName() + ".fileprovider", fileUri);//通過FileProvider創建一個content類型的Uri
}
PhotoUtils.takePicture(Certifica.this, imageUri, PHOTO_REQUEST);
}
/**
* 錄像
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//限制時長
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
//開啓攝像機
startActivityForResult(intent, VIDEO_REQUEST);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//如果按下的是回退鍵且歷史記錄裏確實還有頁面
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_REQUEST) {
if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
if (mUploadCallbackAboveL != null) {
onActivityResultAboveL(requestCode, resultCode, data);
} else if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
} else if (requestCode == VIDEO_REQUEST) {
if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
if (mUploadCallbackAboveL != null) {
if (resultCode == RESULT_OK) {
mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
mUploadCallbackAboveL = null;
} else {
mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
mUploadCallbackAboveL = null;
}
} else if (mUploadMessage != null) {
if (resultCode == RESULT_OK) {
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else {
mUploadMessage.onReceiveValue(Uri.EMPTY);
mUploadMessage = null;
}
}
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
if (requestCode != PHOTO_REQUEST || mUploadCallbackAboveL == null) {
return;
}
Uri[] results = null;
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
results = new Uri[]{imageUri};
} else {
String dataString = data.getDataString();
ClipData clipData = data.getClipData();
if (clipData != null) {
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
results[i] = item.getUri();
}
}
if (dataString != null)
results = new Uri[]{Uri.parse(dataString)};
}
}
mUploadCallbackAboveL.onReceiveValue(results);
mUploadCallbackAboveL = null;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (webView != null) {
webView.setWebViewClient(null);
webView.setWebChromeClient(null);
webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
webView.clearHistory();
// ((ViewGroup) webView.getParent()).removeView(webView);
webView.destroy();
webView = null;
}
}
}
這裏面有個photoUtils,已經封裝好了各種調用,簡單好用
public class PhotoUtils {
private static final String TAG = "PhotoUtils";
/**
* @param activity 當前activity
* @param imageUri 拍照後照片存儲路徑
* @param requestCode 調用系統相機請求碼
*/
public static void takePicture(Activity activity, Uri imageUri, int requestCode) {
//調用系統相機
Intent intentCamera = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intentCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加這一句表示對目標應用臨時授權該Uri所代表的文件
}
intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//將拍照結果保存至photo_file的Uri中,不保留在相冊中
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
if (activity!=null){
activity.startActivityForResult(intentCamera, requestCode);
}
}
/**
* @param activity 當前activity
* @param requestCode 打開相冊的請求碼
*/
public static void openPic(Activity activity, int requestCode) {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
activity.startActivityForResult(photoPickerIntent, requestCode);
}
/**
* @param activity 當前activity
* @param orgUri 剪裁原圖的Uri
* @param desUri 剪裁後的圖片的Uri
* @param aspectX X方向的比例
* @param aspectY Y方向的比例
* @param width 剪裁圖片的寬度
* @param height 剪裁圖片高度
* @param requestCode 剪裁圖片的請求碼
*/
public static void cropImageUri(Activity activity, Uri orgUri, Uri desUri, int aspectX, int aspectY, int width, int height, int requestCode) {
Intent intent = new Intent("com.android.camera.action.CROP");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.setDataAndType(orgUri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", aspectX);
intent.putExtra("aspectY", aspectY);
intent.putExtra("outputX", width);
intent.putExtra("outputY", height);
intent.putExtra("scale", true);
//將剪切的圖片保存到目標Uri中
intent.putExtra(MediaStore.EXTRA_OUTPUT, desUri);
intent.putExtra("return-data", false);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
activity.startActivityForResult(intent, requestCode);
}
/**
* 讀取uri所在的圖片
*
* @param uri 圖片對應的Uri
* @param mContext 上下文對象
* @return 獲取圖像的Bitmap
*/
public static Bitmap getBitmapFromUri(Uri uri, Context mContext) {
try {
// Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), uri);
Bitmap bitmapFormUri = getBitmapFormUri(mContext, uri);
return bitmapFormUri;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 通過uri獲取圖片並進行壓縮
*
* @param uri
*/
public static Bitmap getBitmapFormUri(Context ac, Uri uri) throws FileNotFoundException, IOException {
InputStream input = ac.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;//optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
int originalWidth = onlyBoundsOptions.outWidth;
int originalHeight = onlyBoundsOptions.outHeight;
if ((originalWidth == -1) || (originalHeight == -1)){
return null;
}
//圖片分辨率以480x800爲標準
float hh = 800f;//這裏設置高度爲800f
float ww = 480f;//這裏設置寬度爲480f
//縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可
int be = 1;//be=1表示不縮放
if (originalWidth > originalHeight && originalWidth > ww) {//如果寬度大的話根據寬度固定大小縮放
be = (int) (originalWidth / ww);
} else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的話根據寬度固定大小縮放
be = (int) (originalHeight / hh);
}
if (be <= 0){
be = 1;
}
//比例壓縮
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = be;//設置縮放比例
bitmapOptions.inDither = true;//optional
bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
input = ac.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
input.close();
return compressImage(bitmap);//再進行質量壓縮
}
/**
* 質量壓縮方法
*
* @param image
* @return
*/
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > 100) { //循環判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮
baos.reset();//重置baos即清空baos
//第一個參數 :圖片格式 ,第二個參數: 圖片質量,100爲最高,0爲最差 ,第三個參數:保存壓縮後的數據的流
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//這裏壓縮options%,把壓縮後的數據存放到baos中
options -= 10;//每次都減少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把壓縮後的數據baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream數據生成圖片
return bitmap;
}
/**
* @param context 上下文對象
* @param uri 當前相冊照片的Uri
* @return 解析後的Uri對應的String
*/
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
String pathHead = "file:///";
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return pathHead + Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return pathHead + getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return pathHead + getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return pathHead + getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return pathHead + uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null){
cursor.close();
}
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}