2

我試圖請求Android 6.0的運行時權限。 這是我的代碼:權限READ_EXTERNAL_STORAGE總是被拒絕

private void enablePermission() { 
    String[] PERMISSIONS = { Manifest.permission.READ_EXTERNAL_STORAGE}; 

    if (!hasPermissions(this, PERMISSIONS)) { 
     ActivityCompat.requestPermissions(this, PERMISSIONS, 
       PERMISSION_ALL); 
    } 
} 


public static boolean hasPermissions(Context context, String... permissions) { 

    for (String permission : permissions) { 
     if (ContextCompat.checkSelfPermission(context, permission) != 
       PackageManager.PERMISSION_GRANTED) { 
      return false; 
     } 
    } 

    return true; 
} 


@Override 
public void onRequestPermissionsResult(int requestCode, String[] 
     permissions, int[] grantResults) { 
    switch (requestCode) { 
     case PERMISSION_ALL: 
      if (grantResults.length > 0 && grantResults[0] == 
        PackageManager.PERMISSION_GRANTED) { 
       Log.d("Permission", "Granted"); 
      } else { 
       Log.d("Permission", "Denied"); 
      } 
    } 
} 

它總是告訴我的onRequestPermissionsResult「權限被拒絕」。我試着用ACCESS_FINE_LOCATION這個代碼,它的工作。

回答

0

我解決了我的問題,重啓虛擬設備Genymotion

3

嘗試在您的權限中添加android軟件包。像這樣的東西(這是用於編寫外部存儲):

public boolean isStoragePermissionGranted() { 
    if (Build.VERSION.SDK_INT >= 23) { 
     if (checkSelfPermission(android.Manifest.permission. READ_EXTERNAL_STORAGE) 
       == PackageManager.PERMISSION_GRANTED) { 
      Log.v(TAG,"Permission is granted"); 
      return true; 
     } else { 

      Log.v(TAG,"Permission is revoked"); 
      ActivityCompat.requestPermissions(this, new String[]{Manifest.permission. READ_EXTERNAL_STORAGE}, 1); 
      return false; 
     } 
    } 
    else { //permission is automatically granted on sdk<23 upon installation 
     Log.v(TAG,"Permission is granted"); 
     return true; 
    } 


} 

回調:

@Override 
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     if(grantResults[0]== PackageManager.PERMISSION_GRANTED){ 
      Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]); 
      //resume tasks needing this permission 
     } 
    } 

您可以參考這個SO answer獲取更多信息。