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();
            }
相关推荐
BLUcoding15 分钟前
Android 常用控件及核心属性
android
遥不可及zzz24 分钟前
[特殊字符] Android AAB 一键安装工具配置指南
android·macos
私人珍藏库28 分钟前
【Android】一键硬核锁手机
android·智能手机·app·工具·软件
TTTao23331 小时前
自用Android项目框架备份
android
沃尔威武1 小时前
性能调优实战:从火焰图定位到SQL优化的全流程
android·数据库·sql
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.2 小时前
基于MySQL一主一从环境添加多个新从库
android·mysql·adb
JJay.3 小时前
Android App Functions 深入理解
android
开发_李行4 小时前
简历对应知识点总结--专业技能5
android
网络安全许木4 小时前
自学渗透测试(1~6天工具使用的回温)
android
匆忙拥挤repeat4 小时前
Android Compose 状态保存的API总结
android