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();
            }
相关推荐
范特西林2 小时前
实战演练——从零实现一个高性能 Binder 服务
android
范特西林2 小时前
代码的生成:AIDL 编译器与 Parcel 的序列化艺术
android
范特西林2 小时前
深入内核:Binder 驱动的内存管理与事务调度
android
范特西林3 小时前
解剖麻雀:Binder 通信的整体架构全景图
android
范特西林3 小时前
破冰之旅:为什么 Android 选择了 Binder?
android
奔跑中的蜗牛6665 小时前
一次播放器架构升级:Android 直播间 ANR 下降 60%
android
测试工坊7 小时前
Android 视频播放卡顿检测——帧率之外的第二战场
android
Kapaseker8 小时前
一杯美式深入理解 data class
android·kotlin
鹏多多8 小时前
Flutter使用screenshot进行截屏和截长图以及分享保存的全流程指南
android·前端·flutter
Carson带你学Android8 小时前
OpenClaw移动端要来了?Android官宣AI原生支持App Functions
android