最近公司需要在webview加拍照功能,但是打包后,resultCode一直返回为0,经常两天的调试和修改,最终resultCoe正常返回为-1,问题解决,纪录一下。 直接放代码 private void take() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { String displayName = String.valueOf(System.currentTimeMillis()); ContentValues values = new ContentValues(2); values.put(MediaStore.Images.Media.DISPLAY_NAME, displayName); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //SD 卡是否可用,可用则用 SD 卡,否则用内部存储 imageUri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { imageUri = this.getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } } else { File filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); String pathName = new StringBuffer().append(filePath).append(File.separator) .append(System.currentTimeMillis()).append(".jpg").toString(); // takePictureFile = new File(pathName); // String fileName = "IMG_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg"; file = new File(pathName); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //解决Android 7.0 拍照出现FileUriExposedException的问题 String authority = this.getPackageName() + ".fileProvider"; imageUri = FileProvider.getUriForFile(MainActivity.this, authority, file); } else { imageUri = Uri.fromFile(file); } } //兼容android 7.0+版本的照相机调用代码 Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (captureIntent.resolveActivity(getPackageManager()) != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//输出路径(拍照后的保存路径) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { ContentValues contentValues = new ContentValues(1); contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath()); imageUri = MainActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); } captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); } else { Toast.makeText(this, "照相机不存在", Toast.LENGTH_SHORT).show(); return; } Intent Photo = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); Intent chooserIntent = Intent.createChooser(Photo, "Image Chooser"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent}); startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE); }
其次是要加上权限检查 checkSelfPermission(Manifest.permission .READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED