2017-01-29 57 views
0

讀取外部存儲許可在onCreate方法在版本的Android M錯誤

if (ContextCompat.checkSelfPermission(thisActivity, 
      Manifest.permission.READ_EXTERNAL_STORAGE) 
    != PackageManager.PERMISSION_GRANTED) { 

// Should we show an explanation? 
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, 
     Manifest.permission.READ_EXTERNAL_STORAGE)) { 


} else { 

    ActivityCompat.requestPermissions(thisActivity, 
      new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 
      PERMISSION_REQUEST_CODE); 
} 

在onRequestPermissionsResult

@Override 
public void onRequestPermissionsResult(int requestCode, 
            String permissions[],int[]grantResults) { 
switch (requestCode) { 
    case PERMISSION_REQUEST_CODE: { 

     if (grantResults.length > 0 
      && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
      String path = Environment.getExternalStorageState(); 

     } else { 

     } 
     return; 
    } 
} 

我已經努力嘗試但都崩潰的應用程序結束。權限不被授予應用程序。爲什麼?我做錯了什麼?您的幫助將不勝感激。

+1

你能從日誌發佈異常時崩潰發生? –

+0

AndroidRuntime:致命例外:主要 進程:com.google.android.packageinstaller,PID:14436 java.lang.RuntimeException:無法啓動活動ComponentInfo {com.google.android.packageinstaller/com.android.packageinstaller.permission。 ui.GrantPermissionsActivity}:java.lang.NullPointerException:嘗試獲取空數組的長度 at android.app.ActivityThread.performLaunchActivity – Abdullah

回答

0

我用這個作爲我的代碼,從計算器了,卻忘了誰回答這個問題

public boolean hasPermission(Context context, String... permissions){ 
     for (String permission : permissions) { 
      if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { 
       return false; 
      } 
     } 
     return true; 
    } 
    int PERMISSION_ALL = 1; 
    String[] PERMISSIONS = { 
      Manifest.permission.INTERNET, 
      Manifest.permission.ACCESS_FINE_LOCATION, 
      Manifest.permission.ACCESS_NETWORK_STATE, 
      Manifest.permission.CHANGE_NETWORK_STATE, 
      Manifest.permission.WRITE_SETTINGS, 
      Manifest.permission.CAMERA, 
      Manifest.permission.RECEIVE_SMS, 
      Manifest.permission.SEND_SMS, 
      Manifest.permission.WRITE_EXTERNAL_STORAGE, 
      Manifest.permission.ACCESS_WIFI_STATE, 
      Manifest.permission.CHANGE_WIFI_STATE, 
      Manifest.permission.ACCESS_COARSE_LOCATION, 
      Manifest.permission.READ_CONTACTS}; 
    public void checkAllPermission(){ 
     if (!hasPermission(getActivity(), PERMISSIONS)){ 
      ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, PERMISSION_ALL); 
     } 
    } 
} 

嘗試(如修改您的需要)

+0

我曾嘗試過這種代碼更簡單的形式,但給我同樣的錯誤 – Abdullah

+0

是你的清單已經很好? (完整) –

+0

ntaloventi是的。 – Abdullah

相關問題