AndroidUtilCode Can not uri2File with paht com.google.android.apps.docs.storage

3mpgtkmj  于 2023-02-04  发布在  Android
关注(0)|答案(1)|浏览(135)

Describe the bug

Step 1: Open file selector by Intent ( OS default)
Step 2: select file from Google Drive
Step 3: We have a file with the wrong file name

uri from intent after select file from google drive
content://com.google.android.apps.docs.storage/document/acc%3D3%3Bdoc%3Dencoded%3DGp3qNtSd17JyIvWWjN4kiMe66gjReS6bFjH9yJoRGAp7CAxPF3tSqyiUVZQX6AWznm4%3D

The code of bug

UriUtils.uri2File(selectedFileFromGoogleDrive)

Device:
Samsung A31 - Android 10

mv1qrgav

mv1qrgav1#

Solution work as well for my devices:

object UriUtils {

    fun getFileFromGoogleDrive(context: Context,uri:Uri):File?{
        if (isGoogleDriveUri(uri)) {
            return getDriveFilePath(uri, context)
        }
        return null
    }

    fun isGoogleDriveUri(uri: Uri): Boolean {
        return "com.google.android.apps.docs.storage" == uri.authority || "com.google.android.apps.docs.storage.legacy" == uri.authority
    }

    private fun getDriveFilePath(uri: Uri, context: Context): File? {
        val returnUri: Uri = uri
        val returnCursor: Cursor = context.contentResolver.query(returnUri, null, null, null, null) ?: return null
        /*
     * Get the column indexes of the data in the Cursor,
     *     * move to the first row in the Cursor, get the data,
     *     * and display it.
     * */
        val nameIndex: Int = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
        val sizeIndex: Int = returnCursor.getColumnIndex(OpenableColumns.SIZE)
        returnCursor.moveToFirst()
        val name: String = returnCursor.getString(nameIndex)
        val size = returnCursor.getLong(sizeIndex).toString()
        val file = File(context.cacheDir, name)
        try {
            val inputStream: InputStream = context.contentResolver.openInputStream(uri)!!
            val outputStream = FileOutputStream(file)
            var read = 0
            val maxBufferSize = 1 * 1024 * 1024
            val bytesAvailable: Int = inputStream.available()

            //int bufferSize = 1024;
            val bufferSize = Math.min(bytesAvailable, maxBufferSize)
            val buffers = ByteArray(bufferSize)
            while (inputStream.read(buffers).also { read = it } != -1) {
                outputStream.write(buffers, 0, read)
            }
            Timber.e("Size %s", file.length())
            inputStream.close()
            outputStream.close()
            Timber.e("Path %s", file.getPath())
        } catch (e: Exception) {
            Timber.e(e.message)
        }finally {
            returnCursor.close()
        }
        return file
    }
}

相关问题