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();
            }
相关推荐
得一录3 分钟前
如何将大模型(Gemini)集成到 Android 语音助手中
android·aigc
安卓理事人16 分钟前
鸿蒙中加密库使用
android·java·开发语言
jacGJ17 分钟前
记录解决问题--Android studio generate apks报错error jlink
android·ide·android studio
游戏开发爱好者832 分钟前
在 iOS 开发、测试与上架过程中 如何做证书管理
android·ios·小程序·https·uni-app·iphone·webview
山峰哥36 分钟前
数据库工程实战:一招实现 SQL 查询速度 10 倍提升
android·数据库·sql·编辑器·深度优先
TheNextByte11 小时前
如何将vivo应用程序移至SD卡?综合指南
android
月月玩代码1 小时前
OkHttp,Square出品的Java/Android HTTP客户端!
android·java·okhttp
ii_best1 小时前
按键精灵安卓/IOS手机助手 × 手机按键 App:1 分钟搞定设备连接(超详细教程)
android·ios·智能手机·自动化·编辑器
似霰1 小时前
AIDL Hal 开发笔记4----驱动开发
android·驱动开发·framework·hal
yi诺千金1 小时前
Android U 自由窗口(浮窗)——操作栏相关
android·java·ui