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();
            }
相关推荐
茶栀(*´I`*)28 分钟前
Android 测试入门指南:ADB 基础配置与常用设备管理命令解析
android·adb
gxgldyh3 小时前
Android Framework源码解析(七):BootAnimation 启动流程解析——开机动画是如何显示出来的?
android
达达尼昂3 小时前
在 Claude Cowork 中用好 Claude Fable 5
android·人工智能·后端
sTone873754 小时前
写时复制COW的第一性理解
android·c++·flutter
sTone873754 小时前
Zygote的第一性理解
android
sTone873754 小时前
类RN框架通过Service暴露卡片渲染能力给AI Chat
android·react native
灯火不休4 小时前
Android Studio & Flutter 构建命令完全指南
android
杉氧4 小时前
Ktor 全栈之路 (5):JWT 认证全流程实战 —— 打造安全通信闭环
android·架构·kotlin
️学习的小王4 小时前
Python + MySQL 学生信息管理系统实战教程
android·python·mysql
帅次4 小时前
Android 高级工程师面试:Flutter 路由导航 近1年高频追问 18 题
android·flutter·面试