因为比较简单,就直接上代码吧!
一、布局文件:main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><TextView android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="今天我们来学习怎样使用Android来拨打电话"android:paddingTop="10dp"/><TextView android:text="请输入您要拨打的号码:" android:layout_width="wrap_content"android:layout_height="wrap_content"android:paddingTop="10dp"></TextView><EditText android:id="@+id/tele_no" android:text=""android:layout_width="fill_parent"android:layout_height="wrap_content"android:paddingTop="10dp"></EditText><Button android:id="@+id/btnCall" android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="拨打"android:background="@drawable/blue_button"android:paddingTop="10dp"/></LinearLayout>
二、主界面Activity类:AnyCall.java
publicclass AnyCall extends Activity {private String TAG = "AnyCall";private Button btnCall;private EditText txtTelNO;publicvoid onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);txtTelNO = (EditText) findViewById(R.id.tele_no);btnCall = (Button) findViewById(R.id.btnCall);btnCall.setOnClickListener(new OnClickListener(){publicvoid onClick(View v) {try {String inputStr = txtTelNO.getText().toString();if (isPhoneNumberValid(inputStr)== true) {IntentmyIntentDial = new Intent(Intent.ACTION_CALL,Uri.parse("tel:" +inputStr));startActivity(myIntentDial);} else {Toast.makeText(AnyCall.this, "同学,您的电话格式不对吧",Toast.LENGTH_LONG).show();Log.e(TAG, "电话格式不正确");}} catch (Exception e) {Log.e(TAG, e.getMessage());}}});}publicstaticboolean isPhoneNumberValid(StringphoneNumber) {boolean isValid = false;String expre = "^\\(?(\\d{3})\\)?[-]?(\\d{3})[-]?(\\d{5})$";CharSequence inputStr = phoneNumber;Pattern pattern = Pattern.compile(expre);Matcher matcher = pattern.matcher(inputStr);if(matcher.matches()){isValid = true;}return isValid;}}
三、别忘了在AndroidManifest.xml文件中加上拨打电话的权限:
<uses-permission android:name="android.permission.CALL_PHONE" />
四、如果不想直接拨打电话,而只是弹出拨号窗口,则将调用的Intent改为Intent.ACTION_DIAL:
Intent myIntentDial = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + inputStr));