起因:H5頁面通過openAPP協議喚起客戶端,調用系統照相機,並完成拍照圖片上傳,然后將圖片URL回傳給H5;
后來發現不如讓H5側直接喚起系統照相機,完成拍照后,進行圖片上傳。
一、H5側實現喚起照相機 ,參考自Capturing an Image from the User
相關代碼如下:
<input type="file" accept="image/*" capture>
<input type="file" accept="image/*" capture="user">
<input type="file" accept="image/*" capture="environment">
二、APP實現
1. WebSetting權限
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);
2. WebChromeClient方法復寫
// For Android >= 5.0
@Override
public boolean onShowFileChooser(CustomWebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
uploadMessageAboveL = filePathCallback;
if(fileChooserParams != null && fileChooserParams.isCaptureEnabled()){// 判斷是否使用相機
openCamera();
}else {
openImageChooserActivity();
}
return true;
}
3. 調用系統相機
權限注冊,以及動態申請權限不在本文中,注:android 6.0以后,相機權限需要動態申請。
//用於保存拍照圖片的uri
private Uri mCameraUri;
// 用於保存圖片的文件路徑,Android 10以下使用圖片路徑訪問圖片
private String mCameraImagePath;
// 是否是Android 10以上手機
private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q;
/**
* 調起相機拍照
*/
private void openCamera() {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 判斷是否有相機
if (captureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
Uri photoUri = null;
if (isAndroidQ) {
// 適配android 10
photoUri = createImageUri();
} else {
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
mCameraImagePath = photoFile.getAbsolutePath();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//適配Android 7.0文件權限,通過FileProvider創建一個content類型的Uri
photoUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
} else {
photoUri = Uri.fromFile(photoFile);
}
}
}
mCameraUri = photoUri;
if (photoUri != null) {
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
}
}
}
/**
* 創建圖片地址uri,用於保存拍照后的照片 Android 10以后使用這種方法
*/
private Uri createImageUri() {
String status = Environment.getExternalStorageState();
// 判斷是否有SD卡,優先使用SD卡存儲,當沒有SD卡時使用手機存儲
if (status.equals(Environment.MEDIA_MOUNTED)) {
return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
} else {
return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
}
}
/**
* 創建保存圖片的文件
*/
private File createImageFile() throws IOException {
String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (!storageDir.exists()) {
storageDir.mkdir();
}
File tempFile = new File(storageDir, imageName);
if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
return null;
}
return tempFile;
}
4. 接收照片
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE){
if (null == uploadMessage && null == uploadMessageAboveL) {
return;
}
if (uploadMessageAboveL != null) {
if (Activity.RESULT_OK == resultCode) {
uploadMessageAboveL.onReceiveValue(new Uri[]{mCameraUri});
}else {
uploadMessageAboveL.onReceiveValue(null);
}
uploadMessageAboveL = null;
} else if (uploadMessage != null) {
if (Activity.RESULT_OK == resultCode) {
uploadMessage.onReceiveValue(mCameraUri);
}else {
uploadMessage.onReceiveValue(null);
}
uploadMessage = null;
}
}
}
5. 調用系統相機適配
android 7.0需要配置文件共享.
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
在res目錄下創建文件夾xml ,放置一個文件file_paths.xml(文件名可以隨便取),配置需要共享的文件目錄,也就是拍照圖片保存的目錄。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<!-- 這個是保存拍照圖片的路徑,必須配置。 -->
<external-files-path
name="images"
path="Pictures" />
</paths>
</resources>
參考文章列表:
[Android 調用相機拍照,適配到Android 10]{https://blog.csdn.net/weixin_45365889/article/details/100977510}
[深坑之Webview,解決H5調用android相機拍照和錄像]{https://blog.csdn.net/villa_mou/article/details/78728417}
[android-WebView支持input file啟用相機/選取照片]{https://www.cnblogs.com/maggieq8324/p/11414769.html}