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();
            }
相关推荐
ZHANG13HAO27 分钟前
Android 13 特权应用(Android Studio 开发)调用 AOSP 隐藏 API 完整教程
android·ide·android studio
田梓燊1 小时前
leetcode 142
android·java·leetcode
angerdream1 小时前
Android手把手编写儿童手机远程监控App之JAVA基础
android
菠萝地亚狂想曲2 小时前
Zephyr_01, environment
android·java·javascript
sTone873752 小时前
跨端框架通信机制全解析:从 URL Schema 到 JSI 到 Platform Channel
android·前端
sTone873752 小时前
Java 注解完全指南:从 "这是什么" 到 "自己写一个"
android·前端
catoop2 小时前
Kotlin 协程在 Android 开发中的应用:定义、优势与对比
android·kotlin
撒旦物种2 小时前
Android WebView 获取内容高度
android·webview
空中海2 小时前
第七章:安卓性能优化
android·性能优化
空中海3 小时前
第四章:导航与路由
android