![](/img/trans.png)
[英]Getting a Permission denied error when creating a file with Android, even when permission is given
[英]Able to read file in android even when user permission denied
我正在尝试学习Android编程。 不知道我在做什么错,但是我请求允许从SDCARD读取,并且在测试是否拒绝请求时仍可以读取文件?
在清单中,我有:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
在代码中,我检查权限,但是作为测试,无论权限结果是什么,我都立即调用代码打开并读取文件...无论如何我仍然可以读取文件。
读取文件的代码:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/*");
startActivityForResult(intent, READ_REQ);
我知道我应该在尝试打开文件之前检查许可请求的结果,但是如果未授予许可,Android系统是否不应阻止我读取文件?
(我使用的是Poco F1,MIUI 10,以防万一!)
编辑:添加了获取文件的代码(为简便起见,减少了):
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
}
if(requestCode == READ_REQ){
numbers = readFile(uri);
}
}
}
和
private ArrayList<String> readFile(Uri uri)
{
ArrayList<String> records = new ArrayList<String>();
ArrayList<String> errors = new ArrayList<String>();
InputStream inputStream;
try
{
inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String line;
while ((line = reader.readLine()) != null)
{
// Reads each line in to the array.
}
reader.close();
return records;
}
catch (Exception e)
{
Log.i(LOG_TAG, "Error: " + e);
//System.err.format("Exception occurred trying to read '%s'.", file);
e.printStackTrace();
return null;
}
}
未经允许无法查看,因此您需要在每次用户打开时要求用户允许这种权限
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
// Permission has already been granted
}
如果您以调试模式从Android Studio部署了应用,则默认情况下将授予权限。 在运行应用程序的设备上打开应用程序属性,然后检查授予的权限。 禁用设置后,您的应用将不会询问权限,也不会被授予权限,并且您将无法写入外部存储。 另外,请确保您的设备是Android 6.0或更高版本。 在低于6.0的Android上,始终授予所有权限。
总结-尝试拒绝系统设置的访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.