我正在尝试使用以下代码以编程方式删除Android 9中的文件。该代码在Android 7和Android 8上运行良好,但在Android 9中却无法使用。
删除代码
public void deleteFile(String filePath) {
Log.v("File Path", filePath);
File file = new File(filePath);
if (file.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M || filePath.startsWith("content://")) {
ContentResolver contentResolver = getActivity().getContentResolver();
Uri fileUri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", file);
Log.v("File Uri", ""+fileUri);
if(contentResolver.delete(fileUri, null, null) == 0){
Log.v(">=Marshmallow - File", "File could not be deleted!");
}else{
Log.v(">=Marshmallow - File", "File deleted!");
}
} else {
if (file.delete()) {
dbHelper.deleteFromPDFAll(filePath);
Log.v("File", "File deleted!");
} else {
Log.v("File", "File could not be deleted!");
}
}
} else {
Log.e("File", "File does not exist!");
}
}
清单-提供程序
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
提供者路径(provider_paths.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>
Logcat
2019-07-03 11:37:11.622 15809-15809/com.spicysoftware.pdfviewer V/File Path: /storage/emulated/0/Documents/stammdaten/gem_000004/GemObjekt_00010506.pdf
2019-07-03 11:37:11.623 15809-15809/com.spicysoftware.pdfviewer V/File Uri: content://com.spicysoftware.pdfviewer.provider/external_files/Documents/stammdaten/gem_000004/GemObjekt_00010506.pdf
2019-07-03 11:37:11.626 15809-15809/com.spicysoftware.pdfviewer V/>=Marshmallow - File: File could not be deleted!