1.最近在SDK6.0開(kāi)發(fā)項(xiàng)目組遇到一個(gè)這樣的問(wèn)題:requires Android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission() 2.原因:從6.0(api 23)開(kāi)始, android采用了Runtime permission request, 即在運(yùn)行時(shí)請(qǐng)求權(quán)限,而不是在編譯的時(shí)候,即使在manifest.xml里面添加了權(quán)限也要在運(yùn)行時(shí)請(qǐng)求。 但不是所有的permission都要Runtime request,涉及到資源文件請(qǐng)求時(shí)就會(huì)用到Runtime request,比如獲取位置信息, content provider獲取media的情況。 3.解決方法: a) 首先確認(rèn)在manefist里面添加了READ_EXTERNAL_STORAGE權(quán)限。 b) 在代碼中實(shí)現(xiàn)Runtime request:
@SuppressLint("NewApi") private void requestReadExternalPermission() { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "READ permission IS NOT granted..."); if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) { Log.d(TAG, "11111111111111"); } else { // 0 是自己定義的請(qǐng)求coude requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0); Log.d(TAG, "222222222222"); } } else { Log.d(TAG, "READ permission is granted..."); } }
c)處理請(qǐng)求:
@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { Log.d(TAG, "requestCode=" + requestCode + "; --->" + permissions.toString() + "; grantResult=" + grantResults.toString()); switch (requestCode) { case 0: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted // request successfully, handle you transactions } else { // permission denied // request failed } return; } default: break; } } |
|
來(lái)自: Dragon_chen > 《Android》