我正在尝试学习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;
}
}
答案 0 :(得分:0)
未经许可无法查看,因此您需要在每次用户打开时要求用户允许这种权限
// 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
}
答案 1 :(得分:0)
如果您以调试模式从Android Studio部署了应用,则默认情况下将授予权限。在运行应用程序的设备上打开应用程序属性,然后检查授予的权限。禁用设置后,您的应用将不会询问权限,也不会被授予权限,并且您将无法写入外部存储。另外,请确保您的设备是Android 6.0或更高版本。在低于6.0的Android上,始终授予所有权限。
总结-尝试拒绝系统设置的访问权限。