1、定義名稱strings.xmljava
<resources> <string name="app_name">電話撥號器</string> <string name="action_settings">Settings</string> <string name="please_enter_phone_number">請輸入電話號碼</string> <string name="call">撥打</string> </resources>
2、設計撥號界面main.xmlandroid
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <EditText android:id="@+id/et_phone_number" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/please_enter_phone_number" android:inputType="phone" /> <Button android:id="@+id/btn_dial" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/et_phone_number" android:text="@string/call" /> </RelativeLayout>
3、編寫MyActivity.javaapp
package com.example.test; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MyActivity extends Activity { private Button mDialButton; private EditText mNumberEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mDialButton = (Button) findViewById(R.id.btn_dial); mDialButton.setOnClickListener(new ButtonClickListener()); } private class ButtonClickListener implements OnClickListener { /** * 當按鈕被點擊的時候調用的方法 */ @Override public void onClick(View v) { mNumberEditText = (EditText) MyActivity.this .findViewById(R.id.et_phone_number); //獲取電話號碼 String number = mNumberEditText.getText().toString().trim(); // 判斷電話號碼是否爲空 if (!TextUtils.isEmpty(number)) { //意圖想幹一件什麼事情 Intent intent = new Intent(); intent.setAction(Intent.ACTION_CALL); //數據都是經過Uri進行包裝 intent.setData(Uri.parse("tel:" + number)); startActivity(intent); } else { Toast.makeText(MyActivity.this, R.string.please_enter_phone_number, Toast.LENGTH_SHORT) .show(); } } } }
4、AndroidManifest.xml中添加撥號權限ide
<uses-permission android:name="android.permission.CALL_PHONE" />