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。
相关推荐
志存高远662 小时前
(面试)Android各版本新特性
android
IT从业者张某某2 小时前
信奥赛-刷题笔记-队列篇-T3-P3662Why Did the Cow Cross the Road II S
android·笔记
未来之窗软件服务2 小时前
Cacti 未经身份验证SQL注入漏洞
android·数据库·sql·服务器安全
BXCQ_xuan2 小时前
handsome主题美化及优化:10.1.0最新版 - 2
android
圈圈编码2 小时前
MVVM框架
android·学习·kotlin
橙子199110165 小时前
在 Kotlin 中,什么是解构,如何使用?
android·开发语言·kotlin
androidwork5 小时前
Android 中使用通知(Kotlin 版)
android·kotlin
Digitally6 小时前
如何从 Android 设备打印短信(5 种方法)
android
_龙小鱼_8 小时前
卡顿检测与 Choreographer 原理
android·kotlin