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();
            }
相关推荐
wxson728220 小时前
【Android视频监控系统技术总结】
android·音视频
hunterandroid1 天前
[Android 从零到一] LiveData 粘性事件与单次消费:从重复触发到可靠事件总线
android
hunterandroid1 天前
[Android 从零到一] Android 事件分发机制:从 ACTION_DOWN 到 View 事件消费链路
android
阿巴斯甜1 天前
adb‑shell 全套命令实操总结
android
奔跑的架构师1 天前
[A-49]ARMv9/v8-PSCI接口规范与工作流程简介
android·linux·arm开发·arm
AFinalStone1 天前
Android 7系统国际化(七)Resources 与 AssetManager 源码剖析
android·国际化·local
Android-Flutter1 天前
Android 内存泄漏详解
android·kotlin
catchadmin1 天前
Fiber 与 PHP 8.6 Polling API 异步初探
android·开发语言·php
Android-Flutter1 天前
android Handler , Looper , Message , MessageQueue 详解
android·kotlin