My question is why i need this permission when i'm trying to delete a file from the sdcard, as the permissions says 'Write' it doesn't write anything to the sdcard when i try to delete something so why is this required?
I tried removing the permission, but without it nothing works.
WRITE_EXTERNAL_STORAGE is a dangerous permission which i need to include in my privacy policy and i'm not sure how to explain this.
My permissions
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
My code to delete a file
if (getActivity() != null) {
try {
treeUri = storageUtil.loadTreeUri();
if (!treeUri.equals("")) {
deleteFile(Uri.parse(treeUri), file);
Main.songs.deleteFile(getActivity(), songList.get(position).getData());
Main.songs.reScan(getActivity());
songList = Main.songs.getSongs();
//Send broadcast to update adapters
Intent intent = new Intent(Constants.ACTIONS.BROADCAST_UPDATE_ADAPTER2);
getActivity().sendBroadcast(intent);
if (!songList.isEmpty()) {
allSongsAdapter.updateList(songList);
}
} else if (treeUri.equals("")) {
((MainActivity) getActivity()).getSDCardAccess();
Toast.makeText(getActivity(), "First select directory with music files and try again.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Something went wrong!", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
deleteFile method
private void deleteFile(Uri uri, File file){
if (getActivity() != null){
Intent intent = new Intent(Constants.ACTIONS.BROADCAST_UPDATE_PANEL_STATE);
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
}
if (file.delete()){
Log.i(TAG,"internal delete!");
return;
}
if (getActivity() != null && file.exists()) {
DocumentFile pickedDir = DocumentFile.fromTreeUri(getActivity(), uri);
String filename = file.getName();
try {
getActivity().getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} catch (SecurityException e) {
Log.e(TAG, "SecurityException caught when deleting FilePath!", e);
}
Log.d(TAG, "fileName: " + filename);
if (pickedDir != null) {
DocumentFile documentFile = pickedDir.findFile(filename);
if (documentFile != null && documentFile.exists()) {
if (documentFile.delete()) {
Log.i(TAG, "Delete successful");
} else {
Log.i(TAG, "Delete unsuccessful");
}
}
}
}
}
This is the code i used from another post on here
Android SAF (Storage Access FrameWork): Get particular file Uri from TreeUri