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

Android 撥打電話實作:Intent、Uri 與號碼格式驗證

編輯:關於 Android 程式設計

撥號是手機最基本的動作,但用程式觸發時有幾個細節要注意:Intent 的 Action 選哪個、Uri 前綴怎麼寫、權限別忘了開。本文用一個帶驗證的範例說明。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class A01Activity extends Activity {

    private Button b;
    private EditText et;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        b = (Button) findViewById(R.id.button);
        et = (EditText) findViewById(R.id.et);

        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = et.getText().toString();
                if (isPhoneNumberValid(s) == true) {
                    Intent i = new Intent("android.intent.action.CALL", Uri.parse("tel:" + s));
                    startActivity(i);
                    et.setText("");
                } else {
                    et.setText("");
                    Toast.makeText(A01Activity.this, "您輸入的電話號碼格式錯誤,請重新輸入!",
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    /**
     * 用來判斷電話號碼格式是否正確
     */
    public static boolean isPhoneNumberValid(String phoneNumber) {

        boolean isValid = false;

        /**
         * 用下面的字串規定電話格式:
         * ^\(?     可使用 ( 作為開頭
         * (\d{3})  緊接著 3 個數字
         * \)?      可使用 ) 繼續
         * [- ]?    可選擇性地接一個 "-"
         * (\d{4})  緊接著 4 個數字
         * [- ]?    可選擇性地接一個 "-"
         * (\d{4})$ 以 4 個數字結束
         *
         * 可對照的合法格式範例:
         * (123)456-78900  123-4567-8900  12345678900  (123)-456-78900
         */
        String expression01 = "^\\(?(\d{3})\)?[- ]?(\d{4})[- ]?(\d{4})$";
        String expression02 = "^\\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{5})$";

        Pattern p01 = Pattern.compile(expression01);  // 將電話格式傳入 Pattern
        Matcher m01 = p01.matcher(phoneNumber);       // 檢查格式是否正確

        Pattern p02 = Pattern.compile(expression02);
        Matcher m02 = p02.matcher(phoneNumber);

        if (m01.matches() || m02.matches()) {
            isValid = true;
        }
        return isValid;
    }
}

版面檔很簡單,一個提示文字、一顆按鈕、一個輸入框:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/et"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

權限務必宣告,否則會在執行時丟出 SecurityException:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.my.a01"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" >
        <activity android:name=".A01Activity" android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

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

幾個實務上的選擇

點擊按鈕後,自訂一個 Intent 並傳入 ACTION_CALL 與 Uri.parse("tel:" + 號碼),就會直接撥出。若改用 android.intent.action.DIAL,則是跳系統撥號盤並帶入號碼、由使用者再按撥號鍵——這個版本不需要 CALL_PHONE 權限,上架時也比較不會卡審核,是更推薦的做法。

驗證格式除了寫正則,還有一個更省事的方法:在版面檔的 EditText 加上

android:phoneNumber="true"

即可限制輸入法只允許數字與撥號符號,從源頭減少髒資料。

最後提醒,新版 Android 對 CALL_PHONE 屬高風險權限,需在執行期動態請求,且部分應用商店對此權限的審查相當嚴格,能改用 DIAL 就盡量改用 DIAL。

延伸閱讀:《Android 資源操作技巧匯總》《Android 開發入門與進階教程》《Android 控件用法總結》《Android 短信與電話操作技巧匯總》《Android 多媒體操作技巧匯總》。

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