file.exists() 返回 false,无法播放我的音频文件



当我点击项目时,我正试图从存储中播放音频,由于某种原因,文件返回false for exists((,我有读写外部存储权限,文件在那里,似乎没有损坏,我的文件是.mp4格式,我将作为音频类型播放。

这是我的权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

提供商:

<provider
android:authorities="com.aliaskarurakov.android.mycallrecorderdemo"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>

xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>

这是我的方法:

public void playAudio(){
String path = Environment.getExternalStorageDirectory() + "/tempAudioFile/temp.mp4";
Log.d("path", "onClick: path = "+path);
Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File(path);
Log.i("", "onResponse: name "+file.getName());
if (file.exists()){
Log.i("", "onResponse: I EXIST");
} else {
Log.i("", "onResponse: dont exist?");
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(getUriForFile(context,"com.aliaskarurakov.android.mycallrecorderdemo",file), "audio/*");
context.startActivity(intent);
}

您仍然需要在运行时请求权限。在需要的地方调用此函数。

private void checkReadStoragePermission(){
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_REQUEST_READ_EXTENAL_STORAGE);
}else{
// Do your stuff here if permission is already granted by user
}
}

然后处理用户是否授予。

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
// Here is the permission that you want
case PERMISSION_REQUEST_READ_EXTENAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
// Do your stuff here if permission is granted by user
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

最新更新