【问题标题】:Why android File.delete() , File.rename() fails on some devices?为什么 android File.delete() , File.rename() 在某些设备上失败?
【发布时间】:2018-02-20 13:41:30
【问题描述】:

它适用于我的 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();
        }

【问题讨论】:

标签: android file rename


【解决方案1】:

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

 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 > 24 上的设备时遇到问题,我需要禁用 UriExposure

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

【讨论】:

  • 我已经获得了写权限。我的测试设备 api 级别是 19 和 16。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多