当我单击项目时,我正在尝试播放存储中的音频,出于某种原因,文件为exist()返回false,我已经读写了外部存储权限,并且文件在那里并且似乎没有损坏,我文件为.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);
}
答案 0 :(得分:0)
您仍然需要在运行时请求权限。在需要时调用此函数。
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);
}