unable to Delete File in Android

时间:2019-04-08 13:15:47

标签: java android file

I have tried my solution from StackOverflow but unable to delete file from android

I am getting run time permission. it is in Adapter

File file = new File(/storage/emulated/0/WhatsApp/Media/WhatsApp Video/VID-20190406-WA0004.mp4/VID-20190406-WA0004.mp4
);
                boolean deleted = file.delete();
                file.deleteOnExit();
                Log.d("Delete", String.valueOf(deleted));

                if (!deleted) {
                    boolean deleted2 = false;
                    deleted2 = file.getAbsoluteFile().delete();
                    Log.d("Delete", String.valueOf(deleted2));
                    if (!deleted2) {
                        String dir = file.getAbsolutePath();
                        File f0 = new File(dir, file.getName());
                        boolean d0 = f0.delete();
                        Log.d("Delete", String.valueOf(f0));
                    }
                }

1 个答案:

答案 0 :(得分:0)

Add required permissions to your AndroidManifest.xml if you didn't already:

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Then you should implement runtime permissions at onCreate() method in your MainActivity.

ActivityCompat.requestPermissions(MainActivity.this,
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

Remove file if permission's granted

  @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 1:
            // delete file
         break;
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

Also scan file from media scanner after f0.delete()

MediaScannerConnection.scanFile(context, new String[]{dir}, null, null);