2016-03-05 16 views
1

我正在嘗試檢查應用程序的權限,並且當前正在進行Android開發人員培訓。 但是,在插入page中列出的代碼時遇到了問題。MY_PERMISSONS_REQUEST未定義?

該頁面聲稱MY_PERMISSIONS_REQUEST是一個應用程序定義的int常量。然而,當我把它放在我的實際應用程序中時,它說它沒有被定義...

有人可以解釋爲什麼會出現這種情況嗎? 謝謝!

示例代碼:

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

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

     // Show an expanation to the user *asynchronously* -- don't block 
     // this thread waiting for the user's response! After the user 
     // sees the explanation, try again to request the permission. 

    } else { 

     // No explanation needed, we can request the permission. 

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

     // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an 
     // app-defined int constant. The callback method gets the 
     // result of the request. 
    } 
} 

回答

2

你可能只是把它定義爲一個場不變,就像這樣:

private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1; 

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

這是因爲可能有其他請求。您可以通過您定義的請求代碼與其他人區分。

+0

所以......這只是一個正常的常數?它說它已經是App Defined? – Mildwood

+0

@MinusReputation *應用程序定義*表示您的應用程序定義。那是你定義的常數。不是由Android SDK。 – hata