为什么android File.delete(),File.rename()在某些设备上失败?

时间:2017-09-12 07:33:49

标签: android file rename

它适用于我的nexus 5,但不适用于三星设备和一些OEM设备。

这是我的代码:

 File f = new File(path);
        if (f.exists()) {

            if (f.delete()) {
                MediaScannerConnection.scanFile(ctx, new String[]{path, ""}, null, null);
            } else {
                // Log.e(TAG, ctx.getString(R.string.unableToDelete));
            }

        } else { Toast.makeText(ctx,ctx.getString(R.string.fileNotFound),Toast.LENGTH_SHORT).show();
        }

1 个答案:

答案 0 :(得分:0)

您需要询问用户是否接受读/写权限

 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,}, 1);
        } else {
            createTemporaryFile();
        }

不要忘记添加

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

我在Api上遇到了设备问题&gt; 24使用文件我需要禁用UriExposure

     if(Build.VERSION.SDK_INT>=24){
        try{
            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        }catch(Exception e){
            e.printStackTrace();
        }
    }