274
技術社區[雲棲]
android 撥打電話 號碼判斷
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);
}
});
最後更新:2017-04-02 16:48:17