【发布时间】:2021-03-05 09:30:20
【问题描述】:
我想要的只是我的应用照片可以在手机图库和我的应用内可见。
我想显示我的应用程序以前制作的所有图像并这样做(我删除了一些有关填充 recyclerView 的代码以使其更具可读性):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivPhoto = findViewById(R.id.photo);
photoPaths = new ArrayList<>();
File directory = getExternalFilesDir(Environment.DIRECTORY_DCIM);
File[] files = directory.listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
photoPaths.add(file.getAbsolutePath());
}
}
if (photoPaths.size() > 0) {
File file = new File(photoPaths.get(0));
try {
ExifInterface exif = new ExifInterface(file.getCanonicalPath());
String text = exif.getAttribute(ExifInterface.TAG_EXIF_VERSION);
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
} catch (IOException exception) {
exception.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeFile(photoPaths.get(0));
ivPhoto.setImageBitmap(bitmap);
}
}
我用这种方法从相机拍照:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_PREFIX_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (photoFile == null) {
return;
}
Uri photoURI;
Uri photoURIQ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentValues values = new ContentValues(2);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
photoURIQ = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURIQ);
} else {
photoURI = getUriForFile(this, "com.example.photometadata.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
}
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
上面的代码使照片在图库中可见,但我的应用文件夹中当然没有图片。
我可以更改该代码以使下一张照片在我的应用程序中可见,但这样它们将不会在图库中可见。
我试图从图库中检索照片文件并将其保存到 onActivityResult 中的 getExternalStorageDir() 文件夹,但得到了 EACCESS SecurityExeption。我尝试了其他方法,但没有任何效果。
【问题讨论】:
标签: android android-gallery android-10.0