三步走:
一、先在AndroidManifest.xml声明provider:
<providerandroid:name="androidx.core.content.FileProvider"android:authorities="${applicationId}.FileProvider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/provider_paths"/></provider>
二、创建@xml/provider_paths
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android"><external-path name="external_files" path="."/>
</paths>
三、打开文件:
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();}