2015-11-02 80 views
11

我試圖用下面的代碼編程方式調用了一些:吊銷許可android.permission.CALL_PHONE

String number = ("tel:" + numTxt.getText()); 
Intent intent = new Intent(Intent.ACTION_CALL); 
intent.setData(Uri.parse(number)); 
startActivity(intent); 

我已經設置清單中的權限:

<uses-permission android:name="android.permission.CALL_PHONE"/> 

我m與真正的設備進行測試和調試,它是Nexus 5與Android M,我的compileSdkVersion是23.我得到以下安全例外:

error: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxxxxxxxxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{cbbd7c1 5228:com.dialerTest.DialerApp/u0a96} (pid=5228, uid=10096) with revoked permission android.permission.CALL_PHONE 

我在網上搜索了類似的Q/A並且找不到答案。任何幫助將不勝感激。

回答

13

在android 6.0(Api lvl 23)中,我們有一個名爲「運行時權限」的東西。你必須閱讀它。

你可以找到文件here

+0

謝謝Artur,我已經用文檔教程成功解決了這個問題。我知道在Android上<23安裝許可還會被要求,對嗎? –

+0

@LhuciusHipan是的,爲了向後兼容。 –

7

權限CALL_PHONE屬於危險權限組。
因此,如果您的應用目標SDK爲23或更高,並且您的設備在Android 6.0或更高版本上運行,則必須在應用運行時請求CALL_PHONE權限。

例子:

String number = ("tel:" + numTxt.getText()); 
mIntent = new Intent(Intent.ACTION_CALL); 
mIntent.setData(Uri.parse(number)); 
// Here, thisActivity is the current activity 
if (ContextCompat.checkSelfPermission(thisActivity, 
      Manifest.permission.CALL_PHONE) 
    != PackageManager.PERMISSION_GRANTED) { 

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

    // MY_PERMISSIONS_REQUEST_CALL_PHONE is an 
    // app-defined int constant. The callback method gets the 
    // result of the request. 
} else { 
    //You already have permission 
    try { 
     startActivity(mIntent); 
    } catch(SecurityException e) { 
     e.printStackTrace(); 
    } 
} 

當你的應用程序請求的權限,系統會顯示一個對話框給用戶。當用戶響應時,系統會調用您的應用程序的onRequestPermissionsResult()方法,並將其傳遞給用戶響應。

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

      // permission was granted, yay! Do the phone call 

     } 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 
    } 
}