You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jetpack Compose中使用Intent启动文件选择器

Jetpack Compose 可组合函数内启动文件选择器实现方案

在Compose体系中已经不再推荐使用startActivityForResult处理页面跳转回传,官方提供了专用的rememberLauncherForActivityResult API实现该能力,完整实现代码如下:

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable

@Composable
fun SelectScreen() {
    // 声明文件选择启动器,接收选择结果
    val pickFileLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent(),
        onResult = { selectedFileUri: Uri? ->
            // selectedFileUri为空代表用户取消了选择,不为空则是选中的文件Uri
            selectedFileUri?.let { uri ->
                // 此处编写选中文件后的业务逻辑,例如读取文件、上传等操作
            }
        }
    )

    Button(onClick = {
        // 触发文件选择,入参为需要筛选的文件MIME类型
        pickFileLauncher.launch("*/*")
    }) {
        Text("选择文件")
    }
}

注意:rememberLauncherForActivityResult 必须声明在可组合函数的作用域内,禁止嵌套在点击事件等回调逻辑中声明,否则会引发运行时异常。

可选配置说明

  • 如需筛选特定类型的文件,将launch方法传入的"*/*"替换为对应MIME类型即可,例如选择图片传入"image/*",选择PDF文件传入"application/pdf"
  • 如需支持多选文件,将contract替换为ActivityResultContracts.GetMultipleContents(),对应的onResult回调接收的参数类型为List<Uri>
  • 拿到选中文件的Uri后,可通过context.contentResolver.openInputStream(uri)获取文件输入流,进行后续的读写操作
  • 如果编译时找不到相关API,请确认项目已引入androidx.activity:activity-compose的稳定版本依赖

内容的提问来源于stack exchange,提问作者Hitesh Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 19:54:03