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();
            }
相关推荐
AsiaLYF16 分钟前
kotlin中MutableStateFlow和MutableSharedFlow的区别是什么?
android·开发语言·kotlin
2501_9160088929 分钟前
iOS 发布全流程详解,从开发到上架的流程与跨平台使用 开心上架 发布实战
android·macos·ios·小程序·uni-app·cocoa·iphone
4Forsee38 分钟前
【Android】浅析 Android 的 IPC 跨进程通信机制
android·java
叶羽西1 小时前
如何区分Android、Android Automotive、Android Auto
android
用户2018792831671 小时前
用 “奶茶店订单系统” 讲懂 MVI 架构
android
LiuYaoheng2 小时前
【Android】布局优化:include、merge、ViewStub的使用及注意事项
android·java
Kapaseker2 小时前
Kotlin Flow 的 emit 和 tryEmit 有什么区别
android·kotlin
好好学习啊天天向上3 小时前
Android Studio 撕开安卓手机投屏
android·智能手机·android studio
Android-Flutter4 小时前
android - JPG图片转换HDR图片,heic格式
android
诸神黄昏EX11 小时前
Android Build系列专题【篇四:编译相关语法】
android