如何在Android Q中拍照并保存?

6

新编辑:

我正在开发一款安卓应用并希望支持安卓Q版本。当我的应用在目标API (<= 28) 上运行时,一切都正常。但是在安卓Q上,当我拍照并尝试保存时,出现了一些奇怪的问题。

当我拍摄第一张照片时,我可以在我的自定义照片选择器中找到它。但是在第一张照片之后拍摄的其他照片我就找不到了。

但是我可以使用终端中的adb找到所有的照片。

有人有什么建议吗?

我是这样拍照的:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mCameraFilePath = MediaDataManager.getInstance().getFilePath(MediaDataManager.IMAGE, fileName);
// this function returns the img file path, like /storage/emulated/0/Android/data/<package-name>/files/Pictures/1556592144304.png
mCameraPicUri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".fileprovider", new File(mCameraFilePath));
cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraPicUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);

并保存照片:

try {
    File file = new File(=getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName + ".png");
    if (file.exists()) {
         file.delete();
         file.createNewFile();
    }
     InputStream inputStream = =getContentResolver().openInputStream(mCameraPicUri);
     FileOutputStream out = null;
     try {
         out = new FileOutputStream(file);
         if (inputStream != null) {
               copy(inputStream, out);
               inputStream.close();
         }

         if (out != null) {
             out.close();
         }
     } catch (FileNotFoundException e) {
         e.printStackTrace();
     } catch (IOException e) {
          e.printStackTrace();
     }
}

Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, mCameraPicUri);
sendBroadcast(mediaScanIntent);

以下是copy()方法:

private static final int EOF = -1;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static long copy(InputStream input, OutputStream output) throws IOException {
     long count = 0;
     int n;
     byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
     while (EOF != (n = input.read(buffer))) {
         output.write(buffer, 0, n);
         count += n;
     }
     return count;
}

解决方案: 我应该创建这样的URI:

ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
mCameraPicUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

你是如何保存照片的呢? - Leo
相关链接:https://developer.android.com/preview/privacy/scoped-storage - Morrison Chang
@Morrison Chang 谢谢您的建议,我会尝试的! - Fen Li
我已经编辑了问题。 - Fen Li
1个回答

8

解决方案:我应该按照以下方式创建URI:

ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
mCameraPicUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接