【问题标题】:How to save and check if the file exists in scoped storage?如何保存并检查文件是否存在于范围存储中?
【发布时间】:2021-05-31 09:46:32
【问题描述】:

到目前为止,我检查文件是否存在,如果不存在,则将其保存到 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) 中的设备,但 Android 10 不支持它。

所以我尝试使用 mediastore API 来保存图像。

READ_STORAGE_PERMISSION -> 不允许

首先我使用以下代码查询 contentresolver 以检查文件是否存在:

                Uri collection = null;
                collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
                String[] PROJECTION = new String[]{MediaStore.Images.Media.DISPLAY_NAME,
                        MediaStore.MediaColumns.RELATIVE_PATH};
                String QUERY = MediaStore.Files.FileColumns.RELATIVE_PATH + " like ? and " + 
                MediaStore.Files.FileColumns.DISPLAY_NAME + " like ?";

                ContentResolver mContentResolver = this.getContentResolver();
                Cursor cursor = mContentResolver.query(collection, PROJECTION, QUERY , new String[]{"%" + dirName + "%", "%" + fname + "%"}, null);

                if (cursor != null) {
                    Log.d("upisdk", "cursor != null");
                    if (cursor.getCount() > 0) {

                    } else {
                   
                    }
                }

如果光标为空,则表示文件不存在,我将使用代码保存文件

ContentResolver contentResolver = getContentResolver();
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fname);
                        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
                        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, dirName);
                        Uri imageUri = 
                        contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

                        fos = contentResolver.openOutputStream(Objects.requireNonNull(imageUri));
                        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        Objects.requireNonNull(fos).close();

现在如果在我删除应用数据之前一切正常。

删除数据后,文件夹还在,之前保存的文件也还在。现在,如果查询该文件的内容解析器,则光标为空。如果不允许 READ_STORAGE_PERMISSION,那么它正在发生。如果我允许 READ_STORAGE_PERMISSION 那么它给了我非空游标。另一方面,如果我尝试保存新的不同图像并查询解析器,那么即使没有 READ_STORAGE_PERMISSION,我也会得到非空光标。

请告诉我我做错了什么。

【问题讨论】:

  • I save it to the device in Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) but it is not supported from Android 10. 错误。 Android 10 设备不支持此功能。但它适用于 Android 11 设备。
  • check if the file exists in scoped storage?'对不起。但与范围存储无关。相反,您尝试检查媒体存储中是否存在文件。
  • 如何检查它是否存在于媒体存储中。我可以在文件应用程序中看到它。但是当查询内容解析器时,光标为空
  • 由于文件是由我的应用程序创建的,我应该可以在没有 read_external_storage 的情况下访问该文件
  • 我只想知道图像是否已保存,假设 1234.jpg 已保存并且用户再次想要保存相同的图像,然后我向用户显示它已经保存。

标签: android mediastore android-11


【解决方案1】:

解决方案-1


private fun getUriFromPath(displayName: String): Uri? {
        val photoId: Long
        val photoUri = MediaStore.Images.Media.getContentUri("external")
        val projection = arrayOf(MediaStore.Images.ImageColumns._ID)
        val cursor = contentResolver.query(
            photoUri,
            projection,
            MediaStore.Images.ImageColumns.DISPLAY_NAME + " LIKE ?",
            arrayOf(displayName),
            null
        )!!
        cursor.moveToFirst()
        val columnIndex = cursor.getColumnIndex(projection[0])
        photoId = cursor.getLong(columnIndex)
        cursor.close()
        return Uri.parse("$photoUri/$photoId")
    }

如果您愿意,也可以添加相对路径以在特定位置查找

使用文件名检查

private fun isExist(){
        val pathOfImage=getUriFromPath("myimage.png")
        val isExist = try {
            val i= pathOfImage?.let { contentResolver.openInputStream(it) }
            i != null
        }
        catch (e: IOException) {
            e.printStackTrace()
            false
        }
        if (!isExist) {
            // do whatever u want
        }
    }

此解决方案在找不到文件并尝试打开流时给出异常。



解决方案-2

在这个解决方案中,我确实将文件保存到 Android\media\com.yourpackge\ 目录中

private fun isExist(){
        val path = this.externalMediaDirs.first()
        val folder = File(path, getString(R.string.app_name))
        if (!folder.exists()) folder.mkdirs()
        val  file = File(folder, "myimage.png")

        if (!file.exists()) {
            // save your files or do whatever you want

            // use this for show files into gallery
            MediaScannerConnection.scanFile(this, arrayOf(file.absolutePath), null,
                object : MediaScannerConnection.OnScanCompletedListener {
                    override fun onScanCompleted(path: String, uri: Uri?) {
                        Log.e("scann--","Finished scanning $path")
                    }
                })
        }
    }

现在我想将我的文件从较旧的 getExternalStorageDirectory 文件夹移动到 android 11 中的 Android\media\com.yourpackge\ 目录,就像 whatsapp 在没有征求任何许可的情况下所做的那样。

编辑 - 1

我可以使用 kotlin Utils class 将我的文件夹移动到新文件夹

sourcefolder.copyRecursively(newfolder,true)

private fun copyFiles(){
        val path = this.externalMediaDirs.first()
        val folder = File(path, getString(R.string.app_name))
        if (!folder.exists()) folder.mkdirs()
        val sourcefolder = File(Environment.getExternalStorageDirectory().toString() + "/"
                +"Supreme")
        sourcefolder.copyRecursively(folder,true)

    }

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多