Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

撥打電話時出現 android.permission.CALL_PHONE 權限錯誤的解法

編輯:關於 Android 程式設計

在 App 中直接發起電話撥號,卻在執行時收到 SecurityException,這是權限沒宣告的典型症狀。

錯誤訊息

java.lang.SecurityException: Permission Denial:
starting Intent { act=android.intent.action.CALL dat=tel:xxx-xxx-xxxx
cmp=com.android.phone/.OutgoingCallBroadcaster } from ProcessRecord{406ceac8
342:com.example.ex_37/10043} (pid=342, uid=10043)
requires android.permission.CALL_PHONE

原因

你的應用要直接撥打電話,就必須在功能清單中宣告對應權限。訊息中最後一句 requires android.permission.CALL_PHONE 已經直接點明了缺少哪一項。

解法

在 AndroidManifest.xml 中,<application> 標籤之外加上:

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

完整的結構看起來像這樣:

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.ex_37">

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

    <application
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher" >
        ...
    </application>

</manifest>

宣告的位置很關鍵:<uses-permission> 必須是 <manifest> 的直接子元素,寫進 <application> 裡面是不會生效的。

兩個容易混淆的替代方案

如果你其實不介意多跳一層系統撥號介面,那麼根本不需要 CALL_PHONE 這個權限,改用下列寫法即可:

// 方式 A:只帶號碼,由使用者按撥號鍵確認(不需任何權限)
Intent intent = new Intent(Intent.ACTION_DIAL,
        Uri.parse("tel:0912345678"));
startActivity(intent);

ACTION_DIAL 會開啟撥號盤並把號碼填好,由使用者自行按下撥號;而 ACTION_CALL 則是直接撥出,需要 CALL_PHONE 權限。差別在於「要不要使用者最後確認」。

Android 6.0 以後還要做的事

從 Android 6.0(API 23)開始,CALL_PHONE 被歸類為危險權限,光在 manifest 宣告並不足夠,必須在執行期動態請求:

if (ContextCompat.checkSelfPermission(this,
        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this,
            new String[]{ Manifest.permission.CALL_PHONE }, REQUEST_CALL);
} else {
    callPhone("0912345678");
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                       int[] grantResults) {
    if (requestCode == REQUEST_CALL) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            callPhone("0912345678");
        } else {
            // 使用者拒絕:引導到設定頁,或改用 ACTION_DIAL 讓使用者手動確認
        }
    }
}

private void callPhone(String number) {
    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(Uri.parse("tel:" + number));
    startActivity(intent);
}

使用者拒絕時要有降級方案。實務上常見的做法是退回 ACTION_DIAL:雖然多一步手動確認,但功能仍然可用,也比直接跳錯誤訊息友善得多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved