Android registerForActivityResult

startActivityForResult 已经被标记为不推荐的方法,推荐的替代方案是使用 registerForActivityResult:

Kotlin 复制代码
// Activity 的 onCreate 方法中调用 registerForActivityResult
val activityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->  
    if(activityResult.resultCode == RESULT_OK) {
        val data = activityResult.data
    }
}

//发起请求
activityResultLauncher.launch(intent)

除了 ActivityResultContracts.StartActivityForResult(),ActivityResultContracts 还有很多针对特定功能的其他请求,如动态申请单个或多个权限、选择文件等,选择文件还可以细分为图片、音频、视频等,总之旧代码中使用 startActivityForResult() 的地方,都可以找到对应的替代方案,由于新系统出于对隐私的保护,APP要访问手机任意目录下的文件,需要获得特定的权限,Google Play已经明确,非文件管理器等特殊应用,一般不允许APP使用"访问所有文件"的权限,所以APP如果要存储文件,并且需要导出,基本都是存储在APP专用的目录(Android/data/<packagename>/files),如果需要访问外部存储的文件,比如升级文件等,就使用 ActivityResultContracts.OpenDocument(),代码如下:

Kotlin 复制代码
val activityResultLauncher = registerForActivityResult(ActivityResultContracts.OpenDocument()) {
    it?.let { uri ->
        DocumentFile.fromSingleUri(this, uri)?.let { documentFile ->
            println("file type: " + documentFile.type)
            println("file name: " + documentFile.name)
            Scanner(contentResolver.openInputStream(documentFile.uri)).use { reader ->
                var line: String
                while (reader.hasNextLine()) {
                    line = reader.nextLine()
                    println(line)
                }
            }
        }
    }
}

// 数组类型的参数是 MIME,如果不确定文件类型,就先设置所有类型,即 */*,之后通过 documentFile.type 查看
activityResultLauncher.launch(arrayOf("*/*"))

上面的代码用到了 DocumentFile,主要用来通过 Uri 获取文件信息,如MIME类型、文件名字、文件大小等,需要添加依赖:

Kotlin 复制代码
implementation "androidx.documentfile:documentfile:1.0.1"
相关推荐
阿巴斯甜17 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker17 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq952718 小时前
Andorid Google 登录接入文档
android
黄林晴20 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿1 天前
Android MediaPlayer 笔记
android
Jony_1 天前
Android 启动优化方案
android
阿巴斯甜1 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇1 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_2 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android