Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 撥打電話:Intent 用法與必備權限設定

要在 App 中撥號,核心只有一行 Intent,但真正讓許多人卡住的是權限——少了它,startActivity 會安靜地什麼都不做,或直接丟出 SecurityException。

步驟一:設計簡單的撥號介面

先用畫圖工具構思版面,通常就是一個輸入號碼的 EditText 加一顆「撥打」按鈕。

步驟二:以 Intent 發起通話

Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mobile));
startActivity(intent);

Intent 描述的是「要做什麼事」加上「對象是什麼」。ACTION_CALL 會直接撥出,Uri.parse("tel:...") 則提供號碼。這就像 Windows 的「開始 → 執行」輸入網址,系統會自動找出能處理該 URI 的程式。

步驟三:加入權限

在 AndroidManifest.xml 中宣告:

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

若只想跳到撥號面板而不直接撥出,可改用 Intent.ACTION_DIAL,那就不需要這個權限,也能避免使用者按下撥號前的意外風險。Android 6.0 以上,CALL_PHONE 還必須在執行期向使用者請求授權。

核心程式碼

public class PhoneDuanXINActivity extends Activity {

    private EditText mobileText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mobileText = (EditText) this.findViewById(R.id.mobile);

        Button button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String mobile = mobileText.getText().toString();

                Intent intent = new Intent(Intent.ACTION_CALL,
                                           Uri.parse("tel:" + mobile));
                startActivity(intent);
            }
        });
    }
}

這裡用匿名內部類掛監聽器,因此可以直接存取外部的 mobileText 成員變數。

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">下午好</string>
    <string name="app_name">撥號器</string>
    <string name="mobile">請輸入手機號碼</string>
    <string name="button">撥打</string>
</resources>

實務提醒

送出前應檢查號碼字串是否為空、是否只含數字與 + 號,避免 Uri 解析異常;部分 ROM 對 tel: 的處理略有差異,若遇到問題可先改用 ACTION_DIAL 驗證 Intent 本身是否正確。

Copyright © Linux教程網 All Rights Reserved