File photo = createCaptureFile(encodingType);
if (Build.VERSION.SDK_INT >= 24) {
this.imageUri = new CordovaUri(FileProvider.getUriForFile(cordova.getActivity(),
applicationId + ".provider",
photo));
} else {
this.imageUri = new CordovaUri(Uri.fromFile(photo));
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri.getCorrectUri());
//We can write to this URI, this will hopefully allow us to write files to get to the next step
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
private File createCaptureFile(int encodingType) {
return createCaptureFile(encodingType, "");
}
/**
* Create a file in the applications temporary directory based upon the supplied encoding.
*
* @param encodingType of the image to be taken
* @param fileName or resultant File object.
* @return a File object pointing to the temporary picture
*/
private File createCaptureFile(int encodingType, String fileName) {
if (fileName.isEmpty()) {
fileName = ".Pic";
}
if (encodingType == JPEG) {
fileName = fileName + ".jpg";
} else if (encodingType == PNG) {
fileName = fileName + ".png";
} else {
throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType);
}
// File.createTempFile()
File file = new File(getTempDirectoryPath(), fileName);
if (!file.exists()){
File dir = new File(file.getParent());
dir.mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
private String getTempDirectoryPath() {
File cache = null;
// SD Card Mounted
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cache = cordova.getActivity().getExternalCacheDir();
}
// Use internal storage
else {
cache = cordova.getActivity().getCacheDir();
}
// Create the cache directory if it doesn't exist
cache.mkdirs();
return cache.getAbsolutePath();
}
權(quán)限已開热凹,但是部分手機(jī)外部存儲(chǔ)上寫入時(shí)會(huì)失敗。在getTempDirectoryPath()中cache.mkdirs()返回false,即創(chuàng)建路徑不成功复局,以至于createCaptureFile()中return file 中 的file.exists()=false。當(dāng)調(diào)用相機(jī)的時(shí)候粟判,F(xiàn)ile photo不存在亿昏。解決辦法:在創(chuàng)建文件時(shí),判斷文件是否存在档礁,不存在角钩,new出來。如下:
private File createCaptureFile(int encodingType, String fileName) {
if (fileName.isEmpty()) {
fileName = ".Pic";
}
if (encodingType == JPEG) {
fileName = fileName + ".jpg";
} else if (encodingType == PNG) {
fileName = fileName + ".png";
} else {
throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType);
}
// File.createTempFile()
File file = new File(getTempDirectoryPath(), fileName);
if (!file.exists()){
File dir = new File(file.getParent());
dir.mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}