Android图片未添加到库中,但调用了OnScanCompletedListener



我按照本教程创建了一个示例应用程序,它可以拍摄并保存图片。不幸的是;将照片添加到图库";部件不工作。我在logcat中没有错误。图片在图库中根本看不到。原始代码:

Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);

我试着通过调用MediaScannerConnection.scanFile:来解决这个问题

MediaScannerConnection.scanFile(
getApplicationContext(),
new String[]{f.getAbsolutePath()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
Log.v("MyActivity", "file " + path + " was scanned successfully: " + uri);
}
});

我在logcat中得到这个结果:

file /storage/emulated/0/Android/data/com.example.myapplication/files/Pictures/JPEG_20200804_104708_4760605263689075696.jpg was scanned successfully: content://media/external/file/3524

很遗憾,图片库中仍然没有图片。我做错了什么?怎么可能调试这样的东西?

您的链接告诉您:

注意:如果您将照片保存到getExternalFilesDir((提供的目录中,则媒体扫描程序无法访问这些文件,因为它们对您的应用程序是私有的。。

在Q之前,每个人都可以访问该目录,但显然媒体扫描仪对此视而不见。

但奇怪的是,返回了一个uri。试着打开它。

您可以使用此功能将图像保存到库中,保存后它将立即可见

String name = "image_name";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "Pictures/" + "App Name");
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream outputStream = resolver.openOutputStream(Objects.requireNonNull(imageUri));
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream);
outputStream.flush();
outputStream.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, imageUri));


}catch (Exception e){
e.printStackTrace();
Snackbar.make(v, "Unable to Save image " + e.getMessage(), Snackbar.LENGTH_SHORT).show();
}
}else {
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/App Name";
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
File imageFile = new File(fullPath, name);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream);
outputStream.flush();
outputStream.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile)));
}

相关内容

  • 没有找到相关文章

最新更新