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();
            }
相关推荐
Frank_HarmonyOS38 分钟前
【Android -- 多线程】Handler 消息机制
android
一条上岸小咸鱼1 小时前
Kotlin 基本数据类型(一):概述及分类
android·kotlin
没盐水菠萝2 小时前
Android - 动态切换桌面图标
android
AI 嗯啦2 小时前
SQL详细语法教程(三)mysql的函数知识
android·开发语言·数据库·python·sql·mysql
跨界混迹车辆网的Android工程师3 小时前
adb 发送广播
android
超勇的阿杰5 小时前
gulimall项目笔记:P54三级分类拖拽功能实现
android·笔记
峥嵘life6 小时前
Android 欧盟网络安全EN18031 要求对应的基本表格填写
android·安全·web安全
程序员码歌8 小时前
【零代码AI编程实战】AI灯塔导航-从0到1实现篇
android·前端·人工智能
北十南9 小时前
SODA自然美颜相机(甜盐相机国际版) v9.3.0
android·windows·数码相机
Harry技术9 小时前
Trae搭建Android项目:智能存储柜表结构设计以及实体生成
android·kotlin·trae