2016-11-28 132 views
-1

下面的代碼片段是我用來理解用戶設置的權限,因爲在較新的Android設備中,可以根據設置調整特定應用程序的權限。檢查Android設備中應用程序的運行時權限

我想提醒用戶給予權限以避免應用程序崩潰但以下代碼段總是爲我返回true。我究竟做錯了什麼?

//If authorisation not granted for camera 
boolean permission = (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED); 


if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { 
    //ask for authorisation 
    //Manifest.permission.CAMERA 
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
      Manifest.permission.CAMERA)) { 
     showExplanation("Permission Needed", "Rationale", Manifest.permission.CAMERA, REQUEST_PERMISSION_CAMERA); 
    } 
    else 
     ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA); 
} 
else 
    try { 
     //releasing camera if it's already in use 
     releaseCamera(); 
     camera = Camera.open(camId); 
}catch (Exception e) 
{ 
    e.printStackTrace(); 
} 
+2

*但下面的代碼段對我來說總是返回true *您已授予已授權或在設備上擁有Android版的前棉花糖 – Blackbelt

+0

我正在使用nexus 5 Marshmallowow。我多次嘗試設置和關閉權限。權限始終返回爲true,但我的應用程序崩潰(未授予權限時) –

+0

請參閱此問題http://stackoverflow.com/questions/34342816/android-6-0-multiple-permissions – Radhey

回答

0

我面臨這個問題,因爲這個功能僅在API級別23及更高版本。我正在編譯22.

1
boolean permission = (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED); 

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { 
    //ask for authorisation 
    //Manifest.permission.CAMERA 
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
      Manifest.permission.READ_PHONE_STATE)) { 
     showExplanation("Permission Needed", "Rationale", Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_CAMERA); 
    } 
    else 
     ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA); 
} 
else{ 
    try { 
     //releasing camera if it's already in use 
     releaseCamera(); 
     camera = Camera.open(camId); 
}catch (Exception e) 
{ 
    e.printStackTrace(); 
}} /////// put your else condition in braces 
+0

代碼無用,沒有解釋 –

+0

@Tim Castelijins我剛剛編輯了發佈的代碼,這是很自我解釋的 – Ak9637

+0

我找不到你改變了,請告訴。並請解釋爲什麼您更改了 –

相關問題