2016-09-29 39 views
-1

在Android上,我檢查位置與android marshmallow:如何知道用戶是否拒絕一個應用程序的權限?

LocationManager.isProviderEnabled(GPS_PROVIDER) || LocationManager.isProviderEnabled(NETWORK_PROVIDER) 

這項工作很好用,但是在棉花糖(和上),當用戶在應用設置中去,只有拒絕我的應用程序的權限使用位置(只爲我的應用程序,像mashmallow現在允許這樣做),那麼以前的請求仍然返回true

我嘗試也:

MyActivity.checkSelfPermission('android.permission.ACCESS_FINE_LOCATION') == PERMISSION_GRANTED or MyActivity.checkSelfPermission('android.permission.ACCESS_COARSE_LOCATION') == PERMISSION_GRANTED 

但是,即使用戶拒絕許可t將其總是返回true o我的應用程序

+0

你的targetSdkVersion設置爲? – Michael

+0

到14(我現在不能增加它),但通常它不是不重要?因爲checkSelfPermission只是在api 23上引入的,所以如果targetSdkVersion <23 ...我認爲它們的行爲不同是沒有道理的! – loki

回答

1

確保您已將compileSdkVersiontargetSdkVersion設置爲23在您的build.gradle中。如果它低於23,應用程序將使用舊的權限方法,您提到的方法將不起作用。

+0

感謝kelevandos,但爲什麼這不能與targetSdkVersion <23?增加targetSdkVersion爲23給了我一些其他問題,我現在不想面對:( – loki

+0

)向後兼容性,他們不想破壞舊的權限處理。他們仍然這樣做,但是爲什麼向後兼容性?因爲xD – Kelevandos

+0

checkSelfPermission是在api 23上引入的,所以它們不需要向後兼容? – loki

1

嘗試用下面的代碼:

ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED 
+0

是的抱歉,我錯過了錯誤,我做==和不= =但總是返回true:( – loki

0

checkSelfPermission不返回一個布爾值。它返回一個整數。

這是檢查權限的正確方法:

// Here, thisActivity is the current activity 
if (ContextCompat.checkSelfPermission(thisActivity, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
     != PackageManager.PERMISSION_GRANTED) { 

    // permission is not granted, request it 
    ActivityCompat.requestPermissions(thisActivity, 
       new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
       MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); 

} else {  
    //permision granted 
} 

這是對的方式處理它們

@Override 
public void onRequestPermissionsResult(int requestCode, 
     String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: { 
      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
       && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

       // permission was granted, yay! Do the 
       // contacts-related task you need to do. 

      } else { 

       // permission denied, boo! Disable the 
       // functionality that depends on this permission. 
      } 
      return; 
     } 

     // other 'case' lines to check for other 
     // permissions this app might request 
    } 
} 

從技術文檔

https://developer.android.com/training/permissions/requesting.html

+0

是的,就像這樣我做的:MyActivity.checkSelfPermission('android.permission.ACCESS_FINE_LOCATION')= = PERMISSION_GRANTED,但即使用戶拒絕權限,它也會返回true :( – loki

+0

您是否嘗試過從* ContextCompat調用它*而不是* MyActivity *。你能告訴我們你的代碼嗎? – adalPaRi

1

請參考link。確保你有compileSdkVersion應該是23以上。

在這裏,我創建了代碼,並檢查多個運行時權限,並顯示出理性。

+0

是compileSdkVersion是23(否則我將無法訪問我認爲的checkSelfPermission) – loki

相關問題