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"
相关推荐
小书房4 小时前
Kotlin的by
android·开发语言·kotlin·委托·by
jinanwuhuaguo4 小时前
(第二十八篇)OpenClaw成本与感知的奇点——从“Token封建制”到“全民养虾”的本体论地基
android·人工智能·kotlin·拓扑学·openclaw
xxjj998a5 小时前
Laravel4.x核心特性全解析
android·mysql·laravel
JoshRen5 小时前
2026教程:在Android Termux中集成Gemini 3镜像站实现移动端文档自动处理与摘要生成(附国内免费方案)
android
诸神黄昏EX6 小时前
Android Google KEY
android
一起搞IT吧6 小时前
Android性能系列专题理论之十一:block IO问题分析思路
android·嵌入式硬件·智能手机·性能优化
小妖6667 小时前
怎么用 tauri 创建编译 android 应用程序
android·tauri
鸟儿不吃草8 小时前
安卓实现左右布局聊天界面
android·开发语言·python
xxjj998a10 小时前
Laravel 1.x:PHP框架的原始魅力
android·php·laravel
formula1000010 小时前
在iOS/安卓上远程连接任何 Agent!Claude、Codex、Copilot、Gemini、OpenCode 等
android·copilot