1 package com.example.flexe2;
2
3 import java.util.regex.Matcher;
4 import java.util.regex.Pattern;
5
6 import android.net.Uri;
7 import android.os.Bundle;
8 import android.app.Activity;
9 import android.content.Intent;
10 import android.view.Menu;
11 import android.view.View;
12 import android.view.View.OnClickListener;
13 import android.widget.Button;
14 import android.widget.EditText;
15 import android.widget.Toast;
16
17 /**
18 * Intent拨号
19 *
20 */
21 public class MainActivity extends Activity {
22
23 private Button bt1;
24 private EditText et1;
25
26 @Override
27 protected void onCreate(Bundle savedInstanceState) {
28 super.onCreate(savedInstanceState);
29 setContentView(R.layout.activity_main);
30
31 bt1 = (Button)findViewById(R.id.bt1);
32 et1 = (EditText)findViewById(R.id.et1);
33
34 bt1.setOnClickListener(new OnClickListener() {
35
36 @Override
37 public void onClick(View v) {
38 try {
39 String phoneNum = et1.getText().toString();
40 if(validatePhoneNum(phoneNum)){
41 Intent dailIntent = new Intent("android.intent.action.CALL",Uri.parse("tel:" + phoneNum) );
42 //同下写法
43 //dailIntent.setAction(Intent.ACTION_CALL);
44 //dailIntent.setAction("android.Intent.action.CALL");
45 //dailIntent.setData(Uri.parse("tel:" + phoneNum));
46
47 //拨号键盘
48 dailIntent.setAction(Intent.ACTION_DIAL);
49
50 startActivity(dailIntent);
51 }else{
52 Toast.makeText(MainActivity.this, "PhoneNum Error", Toast.LENGTH_LONG).show();
53 }
54 et1.setText("");
55 } catch (Exception e) {
56 e.printStackTrace();
57 }
58 }
59 });
60 }
61
62 /**
63 * 校验电话号码
64 * @param phoneNum
65 * @return
66 */
67 public boolean validatePhoneNum(String phoneNum) {
68 boolean isValid = false;
69 /* 可接受的電話格式有:
70 * ^\\(? : 可以使用 "(" 作為開頭
71 * (\\d{3}): 緊接著三個數字
72 * \\)? : 可以使用")"接續
73 * [- ]? : 在上述格式後可以使用具選擇性的 "-".
74 * (\\d{3}) : 再緊接著三個數字
75 * [- ]? : 可以使用具選擇性的 "-" 接續.
76 * (\\d{4})$: 以四個數字結束.
77 * 可以比對下列數字格式:
78 * (123)456-7890, 123-456-7890, 1234567890, (123)-456-7890
79 */
80 String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
81 String expression2 = "^\\(?(\\d{2})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
82 String expression3 = "^\\(?(\\d{4})\\)?[\\s]?(\\d{4})[\\s]?(\\d{4})$";
83 Pattern pattern1 = Pattern.compile(expression);
84 Pattern pattern2 = Pattern.compile(expression2);
85 Pattern pattern3 = Pattern.compile(expression3);
86 CharSequence input = phoneNum;
87 Matcher matcher1 = pattern1.matcher(input);
88 Matcher matcher2 = pattern2.matcher(input);
89 Matcher matcher3 = pattern3.matcher(input);
90 if(matcher1.matches()||matcher2.matches()||matcher3.matches()){
91 isValid = true;
92 }
93 return isValid;
94 }
95
96 @Override
97 public boolean onCreateOptionsMenu(Menu menu) {
98 // Inflate the menu; this adds items to the action bar if it is present.
99 getMenuInflater().inflate(R.menu.activity_main, menu);
100 return true;
101 }
102
103
104
105 }