Android 检查 Uri 是否正确、检查Uri是否对应的是图片

一. 使用框架 FileOperator

https://github.com/javakam/FileOperator/blob/master/library_core/src/main/java/ando/file/core/FileUtils.kt#L300 👉 github.com/javakam/Fil…

二. 复制所需代码

FileUtils

/**
 * 检查 Uri 对应的文件是否为 图片
 */
fun checkImage(uri: Uri?): Boolean {
    val options = BitmapFactory.Options()
    options.inJustDecodeBounds = true
    BitmapFactory.decodeFileDescriptor(FileGlobal.openFileDescriptor(uri, FileGlobal.MODE_READ_ONLY)?.fileDescriptor, null, options)
    return options.outWidth != -1
}
/**
 * 1. 检查 Uri 是否正确
 * 2. Uri 对应的文件是否存在 (可能是已删除, 也肯是系统 db 存有 Uri 相关记录, 但是文件失效或者损坏)
 *
 * EN
 * 1. Check if Uri is correct
 * 2. Whether the file corresponding to Uri exists (may be deleted, or the system db has Uri related records, but the file is invalid or damaged)
 *
 * https://stackoverflow.com/questions/7645951/how-to-check-if-resource-pointed-by-uri-is-available
 */
fun checkRight(uri: Uri?): Boolean {
    if (uri == null) return false
    val resolver = FileOperator.getContext().contentResolver
    //1. Check Uri
    var cursor: Cursor? = null
    val isUriExist: Boolean = try {
        cursor = resolver.query(uri, null, null, null, null)
        //cursor null: content Uri was invalid or some other error occurred
        //cursor.moveToFirst() false: Uri was ok but no entry found.
        (cursor != null && cursor.moveToFirst())
    } catch (t: Throwable) {
        FileLogger.e("1.Check Uri Error: ${t.message}")
        false
    } finally {
        try {
            cursor?.close()
        } catch (t: Throwable) {
        }
    }
    //2. Check File Exist
    //如果系统 db 存有 Uri 相关记录, 但是文件失效或者损坏 (If the system db has Uri related records, but the file is invalid or damaged)
    var ins: InputStream? = null
    val isFileExist: Boolean = try {
        ins = resolver.openInputStream(uri)
        // file exists
        true
    } catch (t: Throwable) {
        // File was not found eg: open failed: ENOENT (No such file or directory)
        FileLogger.e("2. Check File Exist Error: ${t.message}")
        false
    } finally {
        try {
            ins?.close()
        } catch (t: Throwable) {
        }
    }
    return isUriExist && isFileExist
}
posted @ 2021-08-17 12:08  javakam  阅读(0)  评论(0)    收藏  举报  来源