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();
            }
相关推荐
2601_9498333920 小时前
flutter_for_openharmony口腔护理app实战+知识实现
android·javascript·flutter
晚霞的不甘20 小时前
Flutter for OpenHarmony从基础到专业:深度解析新版番茄钟的倒计时优化
android·flutter·ui·正则表达式·前端框架·鸿蒙
—Miss. Z—20 小时前
计算机软件资格考试—第二章 操作系统基础知识
文件管理·存储管理·进程管理·设备管理·作业管理
鸟儿不吃草21 小时前
android的Retrofit请求https://192.168.43.73:8080/报错:Handshake failed
android·retrofit
Minilinux201821 小时前
Android音频系列(09)-AudioPolicyManager代码解析
android·音视频·apm·audiopolicy·音频策略
李子红了时21 小时前
【无标题】
android
Android系统攻城狮1 天前
Android tinyalsa深度解析之pcm_close调用流程与实战(一百零四)
android·pcm·tinyalsa·音频进阶·音频性能实战·android hal
weixin_411191841 天前
LifecycleEventObserver和DefaultLifecycleObserver使用
android
、BeYourself1 天前
Intent :跳转与数据传递的正确打开方式
android·android-studio
灵感菇_1 天前
Android 列表控件全面解析:ListView 与 RecyclerView
android·ui