Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

動手做一個 Android 撥號小程式

學習 Android 的路上,動手實作一個能撥打電話的小程式是很好的入門練習。本文將拆解整個流程,從介面設計到 Activity 的程式碼撰寫,一步步帶你完成。

一、設計頁面

我們先規劃一個簡潔的介面:一段提示文字、一個輸入號碼的文字框,以及一顆「撥打」按鈕。

二、Activity 的開發

1. 建立工程
首先在 Android 中建立一個名為 Phone 的工程。

2. 定義字串資源
在 res/values/strings.xml 中寫入資料,藉此實現資料的統一管理:

<string name="input_info">請輸入電話號碼</string>
<string name="dial_caption">撥打</string>

3. 編寫布局
在 layout 的 main.xml 中完成頁面排版:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/input_info" />

<!-- 定義文字輸入框 -->
<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/phone_number" />

<!-- 定義一顆按鈕 -->
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/dial_caption"
    android:id="@+id/dial_btn" />

4. 撰寫 PhoneActivity.java
核心邏輯在於:當使用者點擊按鈕時,取出輸入框中的號碼,包裝成 Intent 並交給系統的撥號服務處理。

package cn.csdn.android;

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

public class PhoneActivity extends Activity {
    EditText numberEt;
    Button dialBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViews();
        dialBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                // 呼叫系統的撥號服務實現電話撥打
                String phone_number = numberEt.getText().toString();
                phone_number = phone_number.trim();
                if (phone_number != null && !phone_number.equals("")) {
                    // 封裝撥打電話的 Intent,並將號碼包裝成 Uri 傳入
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone_number));
                    PhoneActivity.this.startActivity(intent);
                }
            }
        });
    }

    public void findViews(){
        numberEt = (EditText) this.findViewById(R.id.phone_number);
        dialBtn = (Button) this.findViewById(R.id.dial_btn);
    }
}

透過 Intent.ACTION_CALL 搭配 tel: 開頭的 Uri,就能把號碼交給系統撥號程式處理。別忘了在 AndroidManifest.xml 中加上 CALL_PHONE 權限,程式才能順利撥號。

Copyright © Linux教程網 All Rights Reserved