android 撥打電話 號碼判斷
阿新 • • 發佈:2019-01-29
AndroidManifest中新增打電話許可權
<uses-permission android:name="android.permission.CALL_PHONE"/>
public class boda extends Activity { /*宣告Button與EditText物件名稱*/ private Button mButton1; private EditText mEditText1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /*通過findViewById構造器來構造EditText與Button物件*/ mEditText1 = (EditText) findViewById(R.id.myEditText1); mButton1 = (Button) findViewById(R.id.myButton1); /*設定Button物件的OnClickListener來聆聽OnClick事件*/ mButton1.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { try { /*取得EditText中使用者輸入的字串*/ String strInput = mEditText1.getText().toString(); if (isPhoneNumberValid(strInput)==true) { /*建構一個新的Intent 執行action.CALL的常數與通過Uri將字串帶入*/ Intent myIntentDial = new Intent ( "android.intent.action.CALL", Uri.parse("tel:"+strInput) ); /*在startActivity()方法中 帶入自定義的Intent物件以執行撥打電話的工作 */ startActivity(myIntentDial); mEditText1.setText(""); } else { mEditText1.setText(""); Toast.makeText( boda.this, "輸入的電話格式不符", Toast.LENGTH_LONG).show(); } } catch(Exception e) { e.printStackTrace(); } } }); } /*檢查字串是否為電話號碼的方法,並返回true or false的判斷值*/ public static boolean isPhoneNumberValid(String phoneNumber) { boolean isValid = false; /* 可接受的電話格式有: * ^\\(? : 可以使用 "(" 作為開頭 * (\\d{3}): 緊接著三個數字 * \\)? : 可以使用")"接續 * [- ]? : 在上述格式後可以使用具選擇性的 "-". * (\\d{4}) : 再緊接著三個數字 * [- ]? : 可以使用具選擇性的 "-" 接續. * (\\d{4})$: 以四個數字結束. * 可以比較下列數字格式: * (123)456-78900, 123-4560-7890, 12345678900, (123)-4560-7890 */ String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$"; String expression2 ="^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$"; CharSequence inputStr = phoneNumber; /*建立Pattern*/ Pattern pattern = Pattern.compile(expression); /*將Pattern 以引數傳入Matcher作Regular expression*/ Matcher matcher = pattern.matcher(inputStr); /*建立Pattern2*/ Pattern pattern2 =Pattern.compile(expression2); /*將Pattern2 以引數傳入Matcher2作Regular expression*/ Matcher matcher2= pattern2.matcher(inputStr); if(matcher.matches()||matcher2.matches()) { isValid = true; } return isValid; } }
跳轉到撥打電話介面
myImageButton = (ImageButton) findViewById(R.id.myImageButton); myImageButton.setOnClickListener(new ImageButton.OnClickListener() { @Override public void onClick(View v) { /* 呼叫撥號的畫面 */ Intent myIntentDial = new Intent("android.intent.action.CALL_BUTTON"); startActivity(myIntentDial); } });