Android 中 打开文件选择器(ACTION_OPEN_DOCUMENT )

在 Android 中,打开文件选择器(File Picker)通常是指启动一个系统提供的界面,让用户可以选择存储在设备上的文件。可以通过发送一个带有 Intent.ACTION_OPEN_DOCUMENT 或 Intent.ACTION_GET_CONTENT 的 Intent 来实现。

1、启动文件选择器

Intent.ACTION_OPEN_DOCUMENT 和 Intent.ACTION_GET_CONTENT 都是一个系统提供的 Intent 动作,用于启动一个文件选择器,允许用户选择存储在设备上的文件。这个动作返回一个 Uri,指向用户选择的文件。

cpp 复制代码
package com.example.helloworld.file

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.example.helloworld.R

class FileActivity: AppCompatActivity() {

    private val pickFileLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK && result.data != null) {
            val uri: Uri? = result.data?.data
            uri?.let {
                // 处理选择的文件 URI
                Toast.makeText(this, "Selected file URI: $uri", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file)

        val button:Button = findViewById(R.id.file_packer)
        button.setOnClickListener {
            startFilePacker()
        }
    }

    /**
     * 启动文件选择器
     */
    private fun startFilePacker() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            addCategory(Intent.CATEGORY_OPENABLE)
            // 允许选择所有类型的文件, 若为PDF文件,则类型为 application/pdf
            type = "*/*"
        }
        pickFileLauncher.launch(intent)
    }
}

2、权限说明

  • 如果你需要访问文件的内容,可能需要请求 READ_EXTERNAL_STORAGE 权限。
  • 从 Android 11 开始,WRITE_EXTERNAL_STORAGE 权限不再提供对所有文件的访问权限。
  • 从 Android 10 开始,应用需要遵循分区存储规则。使用 Intent.ACTION_OPEN_DOCUMENT 或 Intent.ACTION_GET_CONTENT 是符合分区存储的设计原则的。
  • 获取到的文件 URI 是一个 content:// URI,而不是文件路径。如果需要访问文件的路径,可以使用 ContentResolver。
相关推荐
出门吃三碗饭7 小时前
如何在LLM大语言模型上微调来优化数学推理能力?
android·人工智能·语言模型
shaominjin1238 小时前
Android访问OTG文件全解析:从连接到操作的完整指南Android系统访问U盘的实现机制与操作指南
android
游戏开发爱好者811 小时前
HTTPS 内容抓取实战 能抓到什么、怎么抓、不可解密时如何定位(面向开发与 iOS 真机排查)
android·网络协议·ios·小程序·https·uni-app·iphone
Tom4i13 小时前
Android 系统的进程模型
android
介一安全13 小时前
【Frida Android】基础篇9:Java层Hook基础——Hook构造函数
android·网络安全·逆向·安全性测试·frida
杨筱毅13 小时前
【Android】Compose绘制系统 VS 传统View绘制系统
android
介一安全13 小时前
【Frida Android】基础篇10:Native层Hook基础--普通 Hook
android·网络安全·逆向·安全性测试·frida
位步14 小时前
在linux系统中使用通用包安装 Mysql
android·linux·mysql
生莫甲鲁浪戴15 小时前
Android Studio新手开发第二十六天
android·前端·android studio
sky0Lan16 小时前
一个类似 pytest 的 html 报告
android·html·pytest