在外部存储中创建新文件时拒绝权限

时间:2015-09-09 13:45:39

标签: android android-external-storage

如果该文件不存在,我想在外部存储中创建一个新文件。 我已经在SO中阅读了类似的问题,并且在我的清单中有WRITE_EXTERNAL_STORAGE个权限。 使用Android 5.1测试GenyMotion模拟器,使用android 4.3测试xperia,结果相同,我在file.createNewFile()上获得“打开失败:EACCES(权限被拒绝)”。我在运行时检查了getExternalStorageState functoin返回值是“ MOUNTED”

注意:如果我手动创建文件,我的代码可以正常工作并读取内容,这意味着访问外部存储是可以的。 我虽然使用getExternalPublicStorage写入我的代码中的另一个地方的外部存储器来保存捕获的图像,但它工作正常!

File f = Environment.getExternalStorageDirectory();
File config = new File(f, "poinila config" + ".txt");
if (!config.exists()) {
    if (!config.createNewFile()) {
        // toast that creating directory failed
    } else {
        writeDefaultIpPort();
    }
}

修改    path string是“/ storage / sdcard0 / poinila config.txt”

1 个答案:

答案 0 :(得分:1)

我认为这是android中引入的新安全功能。运行时权限。你必须做这样的事情

           int hasReadExternalStoragePermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
            if(hasReadExternalStoragePermission != PackageManager.PERMISSION_GRANTED)
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE))
                    new AlertDialog.Builder(getContext())
                            .setMessage("You need to Allow access to Images to set a Company Logo")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    requestPermission();
                                }
                            }).show();
                    else
                        requestPermission();
            else
                callChooser();