如何在自定义文件夹中使用 ContentResolver 添加数据?

How to add data with ContentResolver in custom folder?

我在 Pictures 文件夹中创建了 MyAppImages 文件夹。我想在此文件夹中保存一张新图像。

当我通过ContentResolver插入MediaStore.Image.Media.EXTERNAL_CONTENT_URI时,我可以将图片直接保存到图片文件夹中。

当我使用 FileProvider 通过 uri 添加我自己的文件夹时,出现 java.lang.UnsupportedOperationException: No external inserts 错误。

当我用 Uri.fromFile(myDirFile) 添加我自己的文件夹时,我得到 java.lang.IllegalArgumentException: Unknown URL file:///storage/emulated/0/Android/data/com.my.app/files/Pictures/MyApp%20Image 错误。但是,当我调用 myDirFile.exists() 时,它 returns 为真。

我的代码:

private void saveByteToFile(byte[] byteArray, String contentType, long seconds){

 File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                        
 //getOrCreate MyApp Images directory
 File myDirFile = new File(attachmentDir.getAbsolutePath(), "MyApp Images"); 

 //first error I mentioned
 //Uri myDirUri = FileProviderUtil.getUriFor(MyApplication.getContext(), myDirFile); 
 //second error I mentioned
 Uri myDirUri = Uri.fromFile(myDirFile);
        
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
   if (!myDirFile.exists())
        Files.createDirectory(Paths.get(myDirFile.getAbsolutePath()));
 } else {
      myDirFile.mkdirs();
 }

 Logger.i(myDirFile.exists() + " myDirUri: " + myDirUri); //exists return true

 ContentValues contentValues = new ContentValues();
 contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
 contentValues.put(MediaStore.MediaColumns.MIME_TYPE, contentType);
 contentValues.put(MediaStore.MediaColumns.DATE_ADDED, seconds);
 contentValues.put(MediaStore.MediaColumns.DATE_MODIFIED, seconds);
 contentValues.put(MediaStore.Images.Media.DATA, myDirFile.getAbsolutePath());

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
 contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
 }

 ContentResolver resolver = getContext().getContentResolver();
 try {
    Uri outputUri = resolver.insert(myDirUri, contentValues); //->the errors I mentioned here are returning

    if (outputUri == null)
        throw new IOException("Failed to create new MediaStore record.");

        try (final OutputStream stream = resolver.openOutputStream(outputUri)) {
           if (stream == null)
               throw new IOException("Failed to open output stream.");

               stream.write(byteArray);

        } finally {
           if (Build.VERSION.SDK_INT > 28) {
               ContentValues updateValues = new ContentValues();
               updateValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
               resolver.update(outputUri, updateValues, null, null);
           }
        }

           return outputUri;
        } catch (IOException e) {
            Logger.exception(e);
            throw e;
        }
}

看看这个可能对你有帮助..

private fun saveImage(bmp: Bitmap) {
    var imageOutStream: OutputStream
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val values = ContentValues()
        //image name
        values.put(MediaStore.Images.Media.DISPLAY_NAME, "image.jpg");
        // image type
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        //storage path
        values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/" + "Camera");

        val uri = requireContext().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        imageOutStream = uri?.let { requireContext().getContentResolver().openOutputStream(it) }!!
    }

    else
    {
        //creating directory and saving
        val imagesDir =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()
        val image = File(imagesDir, "image.jpg")
        imageOutStream =  FileOutputStream(image);

    }
    //compreesing the image
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, imageOutStream);
    Toast.makeText(requireContext(),"ImageSaved",Toast.LENGTH_LONG).show()
    imageOutStream.close();

}