问题描述
我正在尝试使用相机意图拍摄图像并将其保存在文件夹中。该代码在其他 Android 版本(最高 Android 10)中运行良好。但相同的代码未在 Android 11 上运行。我也在使用自定义摄像机录制视频,但它在 Android 11 中也运行良好。请帮助我。
相机代码:-
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = Utilites.createImageFile(photocount,getActivity());
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(getActivity(),"Catched No Directory",Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent,CAMERA_CAPTURE);
} else {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,CAMERA_CAPTURE);
}
} else {
Toast.makeText(getActivity(),"No Directry",Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(),"Take pic intent null",Toast.LENGTH_SHORT).show();
}
创建图像文件的实用程序类代码。保存图片的文件夹名称以服务器生成的编号为准。
public static File createImageFile(int id,Activity activity) throws IOException {
String mCurrentPhotoPath;
// Create an image file name
String imageFileName = "";
File storageDir = new File(activity.getFilesDir() + "/Photos/" + Job_inspections_Activity.LeadID + "/Pictures/");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
String directory = storageDir.toString();
for (int i = 1; i <= id; i++) {
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
File file = new File(directory + "/" + ts + "-" + i + "~Photo.jpg");
if (file.exists()) {
// do nothing
// as the image already exists and if we do anything it might override it
//so leave this condition as it is.
} else {
// if the given file name is not found then pass the first name that is encountered and do not exists.
// and then break the loop as it useless to continue to do so.
imageFileName = ts + "-" + i + "~Photo.jpg";
break;
}
}
File image = new File(storageDir,imageFileName);
/*File.createTempFile(
imageFileName,*//* prefix *//*
".jpg",*//* suffix *//*
storageDir *//* directory *//*
);*/
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
我已经检查了模拟器的设备资源管理器,它显示了使用上述方法创建的文件,但相机在结果代码中始终返回 0(零)。
我的模块级 build.gradle 文件信息
compileSdkVersion 29
buildToolsversion "28.0.3"
minSdkVersion 19
targetSdkVersion 29
我在 Logcat 中也没有收到任何警告/错误消息。
针对这个问题,我尝试了很多解决方案,但都没有奏效。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)