Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實作撥打電話功能

編輯:關於 Android 程式設計

Android 實作撥打電話功能

本例需要一個輸入框輸入號碼,以及一個撥打按鈕,本質是點擊按鈕後呼叫系統的撥號功能。

版面配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="請輸入號碼" />
    <EditText
        android:id="@+id/et_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/bt_call"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="撥打" />
</LinearLayout>

MainActivity

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button bt = (Button) findViewById(R.id.bt_call);
        bt.setOnClickListener(new MyListener());
    }

    class MyListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            EditText et = (EditText) findViewById(R.id.et_phone);
            String phone = et.getText().toString();
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_CALL);          // 直接撥打
            intent.setData(Uri.parse("tel:" + phone));     // tel: 協定不可省略
            startActivity(intent);
        }
    }
}

說明:Intent.ACTION_CALL 會直接撥號,需加上 CALL_PHONE 權限並執行期請求;若只想跳到撥號盤由使用者確認,可改用 Intent.ACTION_DIAL,則不需該權限。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved