android.permission.WRITE_EXTERNAL_STORAGE已授予但访问被拒绝

时间:2016-07-28 14:07:24

标签: android file android-permissions

以下代码输出是“Write written”但在此之后错误'/ storage_emulated/0/Download/test.txt:open failed:EACCES(Permission denied)'

怎么了?

@RunWith(AndroidJUnit4.class)
public class FileStorageTest {

    private static final String TAG = FileStorageTest.class.getSimpleName();

    @Test
    public void test() throws Exception {
        Context context = InstrumentationRegistry.getTargetContext();
        if (context.checkSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "Write granted");
        } else {
            Log.e(TAG, "Write refused");
        }

        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"test.txt");
        new FileOutputStream(file).close();
    }
}

2 个答案:

答案 0 :(得分:1)

  

您还需要添加READ_EXTERNAL_STORAGE权限才能从设备读取数据。

     

也在RunTime添加此权限。

    if (context.checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "Read granted");
    } else {
            Log.e(TAG, "Read refused");
    }

答案 1 :(得分:0)

尝试将此添加到您的清单文件中:

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