[英]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.