android.permission.WRITE_EXTERNAL_STORAGE 授予但访问被拒绝
android.permission.WRITE_EXTERNAL_STORAGE granted but access denied
下面的代码输出是 "Write granted" 但之后出现错误 '/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();
}
}
尝试将其添加到您的清单文件中:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You need to also add READ_EXTERNAL_STORAGE
permission to read data from the device.
Add this permission also at RunTime
.
if (context.checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Read granted");
} else {
Log.e(TAG, "Read refused");
}
下面的代码输出是 "Write granted" 但之后出现错误 '/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();
}
}
尝试将其添加到您的清单文件中:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You need to also add
READ_EXTERNAL_STORAGE
permission to read data from the device.Add this permission also at
RunTime
.
if (context.checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Read granted");
} else {
Log.e(TAG, "Read refused");
}