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

Android 開發:實作簡易電話撥號器

編輯:關於 Android 開發

以下示範如何製作一個簡單的電話撥號器,讓使用者輸入號碼後按下按鈕即可撥打。

AndroidManifest.xml 清單檔

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="eoe.phone"
    android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon"
        android:label="@string/app_name">
        <activity android:name=".MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.CALL_PHONE"/>
</manifest>

請特別注意,撥打電話必須加入 android.permission.CALL_PHONE 權限。

main.xml 版面配置

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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="請輸入手機號碼" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/phone" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="撥打此號碼"
        android:id="@+id/button" />
</LinearLayout>

MainActivity 類別

package com.ljq.phone;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
    private EditText phone = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        phone = (EditText) this.findViewById(R.id.phone);
        Button button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                String tel = phone.getText().toString();
                // 方法二:直接以帶有 action 的建構子建立 Intent
                Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + tel));
                // 該方法內部會自動為 intent 設定類別:android.intent.category.DEFAULT
                startActivity(intent);
            }
        });
    }
}

核心邏輯是以「tel:」加上號碼組成 URI,再搭配 ACTION_CALL 這個 Intent 觸發撥號,系統便會自動啟動電話應用程式。

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