萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 撥打電話權限申請與撥號器啟動完整指南

權限聲明 (AndroidManifest.xml)

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

    <!-- API 23+ 執行時權限,必須聲明 -->
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <!-- 若僅需開啟撥號介面由用戶確認,使用 ACTION_DIAL 無需權限 -->
    <uses-permission android:name="android.permission.CALL_PRIVILEGED" /> <!-- 系統級,一般應用不可用 -->
</manifest>

兩種撥號方式選擇

Intent Action行為需權限適用場景
ACTION_DIAL開啟撥號器預填號碼,**用戶需手動點擊撥打鍵****無**尊重用戶意願、合規、推薦
ACTION_CALL**直接撥打電話**,無用戶確認CALL_PHONE (危險權限)自動化測試、企業內部工具、緊急呼叫

執行時權限請求流程 (Kotlin + Activity Result API)

class MainActivity : ComponentActivity() {
    private val requestCallPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
        if (granted) dialNumber(phoneNumber) else showPermissionRationale()
    }

    private lateinit var phoneNumber: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val etPhone = findViewById(R.id.etPhone)
        val btnCall = findViewById

佈局檔 (res/layout/activity_main.xml)

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="24dp"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="請輸入電話號碼:"
        android:textSize="18sp" />

    <EditText
        android:id="@+id/etPhone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:hint="09xxxxxxxx" />

    <Button
        android:id="@+id/btnCall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="直接撥打 (需權限)" />

    <Button
        android:id="@+id/btnDial"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="開啟撥號器 (免權限)" />
</LinearLayout>

常見坑與解決

  • 號碼格式:Uri.parse("tel:+886912345678") 支援國際格式;特殊字元 (*、#、逗號暫停) 需 Uri.encode。
  • 雙 SIM 卡:Android 5.1+ SubscriptionManager 可指定 SIM 槽,但需系統簽名權限,一般應用無法控制。
  • 緊急電話:110、119、911 等無需 SIM 卡即可撥打,ACTION_CALL 同樣適用。
  • Google Play 政策:非核心通訊功能應用若申請 CALL_PHONE 需填寫權限聲明表單,否則會被拒。優先使用 ACTION_DIAL。

測試檢查清單

  1. 授權對話框正確顯示、拒絕後引導去設定頁。
  2. 授權後立即撥打/開啟撥號器無崩潰。
  3. 號碼含特殊字元、國際碼正確識別。
  4. 無通話應用裝置 (平板/模擬器) 彈出友善提示。
  5. 權限撤銷後再次點擊正確重新請求。

遵循「最小權限、用戶確認、優雅降級」原則,讓撥號功能既合規又好用。

copyright © 萬盛學電腦網 all rights reserved