Android:文件管理:打开文件意图

三步走:

一、先在AndroidManifest.xml声明provider:

html 复制代码
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

二、创建@xml/provider_paths

html 复制代码
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

三、打开文件:

java 复制代码
            Intent intent = new Intent(Intent.ACTION_VIEW);
            File file = new File("/sdcard/Music/音乐文件.mp3");
            // "com.example.myapplication.FileProvider"对应AndroidManifest.xml声明的android:authorities="${applicationId}.FileProvider"
            Uri uri = FileProvider.getUriForFile(getApplicationContext(), "com.example.myapplication.FileProvider", file);
            // 其他类型根据你实际的文件来
            intent.setDataAndType(uri, "audio/mp3");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                startActivity(intent);
            } catch (Exception e) {
                Toast.makeText(this, "没有找到播放音频的应用", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
相关推荐
Mr.pyZhang4 小时前
Android构建系统 - 04 编译产物
android·linux
守城小轩10 小时前
Brave 132 编译指南 Android 篇 - 编译准备:系统要求与推荐工具 (三)
android·chrome·chrome devtools·指纹浏览器·浏览器开发·brave
m0_7482384210 小时前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
程序员江同学11 小时前
Kotlin 技术月报 | 2025 年 2 月
android·kotlin
甜于酸12 小时前
MuMu模拟器Pro for Mac 安卓手机平板模拟器
android·macos·智能手机
顾林海15 小时前
深入解析 Android Activity 生命周期
android
XuanRanDev16 小时前
【构建工具】Gradle Kotlin DSL中的大小写陷阱:BuildConfigField
android·开发语言·kotlin
Nathan2024061619 小时前
Room - 基本使用及使用问题
android·面试·android jetpack
攻城狮_Dream21 小时前
基于 Python 的项目管理系统开发
android·数据库·python
zhangphil21 小时前
Android AsyncLayoutInflater异步加载xml布局文件,Kotlin
android·kotlin