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

Android 入門實作(一):打造一個會撥號的電話聯絡人 App

編輯:關於 Android 程式設計

這是 Android 學習系列的第一篇,用最經典的「撥打電話」當作切入點,順便把專案結構、四大組件的基本概念與 Activity 生命週期一起梳理一遍。

一、先搞清楚專案結構

建立一個新專案之後,各個資料夾的職責如下:

  • src:Java 源碼目錄,邏輯上只允許一個包。
  • gen:自動產生的 R.java。修改資源後系統會重新產生,其中 drawable 類別對應 res 下的 drawable 目錄,layout 對應 layout 目錄,string 對應 values 中的字串資源。
  • assets:存放較大的靜態檔案,例如視頻、音頻、字體(1GB 以內不會被編譯)。
  • res:資源檔總目錄。drawable 放圖片,layout 放介面佈局(main.xml),values 放字串與顏色(strings.xml)。
  • AndroidManifest.xml:清單檔,描述應用程式的構成、組件與權限。

編譯後,Java 程式碼會變成 classes.dex,這才是 Android 平台上真正可執行的二進位碼。

二、Android 的 API 分層速覽

  • android.app:高層程式模型,提供基本的應用運行環境
  • android.content:對裝置上資料進行存取與發布
  • android.database:透過內容提供者瀏覽與發布資料
  • android.graphics:底層繪圖函式庫
  • android.location:定位與相關服務
  • android.media:管理音訊、視訊等多媒體與其介面
  • android.net:網路存取相關的類別
  • android.os:系統服務、訊息傳遞與 IPC 機制
  • android.opengl:OpenGL 工具
  • android.provider:存取 Android 的內容提供者
  • android.telephony:與撥打電話相關的 API 互動
  • android.view:基礎使用者介面框架
  • android.util:各類工具方法
  • android.webkit:預設瀏覽器介面
  • android.widget:各種 UI 元素

而 Android 程式的核心組件包括:View(介面視圖與 UI 控制)、Intent(意圖,支援組件間通訊)、Activity(處理介面)、IntentReceiver(接收訊息與事件)、Service(後台服務)以及 Notification(訊息與通知)。

三、Activity 與它的生命週期

一個 Activity 就是一個應用程式組件,它提供一個螢幕讓使用者可以互動以完成某項任務,例如撥號、拍照、寄信、看地圖。每個 Activity 都被賦予一個視窗,可以在上面繪製使用者介面;視窗通常填滿整個螢幕,但也可以小於螢幕而浮在其他視窗之上。

一個應用程式通常由多個鬆耦合的 Activity 組成。其中會有一個被指定為「main」的 Activity,也就是第一次啟動應用時呈現給使用者的那一個;每個 Activity 之後都可以啟動另一個 Activity 去完成不同的動作。

每當一個 Activity 被啟動,前一個就停止了,但系統會把它保留在堆疊上(back stack)。新的 Activity 被推到堆疊頂端並取得焦點。Back Stack 遵循簡單的「後進先出」原則,因此當使用者完成目前 Activity 並按下返回鍵,它會被彈出堆疊(並被摧毀),先前的 Activity 隨即恢復。

生命週期相關的回呼方法:

void onCreate(Bundle savedInstanceState)
void onStart()
void onRestart()
void onResume()
void onPause()
void onStop()
void onDestroy()

其中最重要的是兩個:onCreate() 必須實作,系統在建立 Activity 時呼叫它,在這裡初始化基本組件,更重要的是必須呼叫 setContentView() 來定義使用者介面;onPause() 則在使用者離開你的 Activity 時被呼叫(雖然不總是意味著 Activity 被摧毀),通常應該在這裡提交那些需要跨過 user session 而存在的變更。

另外,Activity 因新的 Activity 啟動而停止時,會透過這些生命週期回呼收到通知。應該在 onStop / onPause 中釋放大的物件(例如網路或資料庫連線),並在 onResume 時重新取得必要資源、恢復被中斷的操作。

四、使用者介面的兩種建立方式

一個 Activity 的介面由層次化的 View 物件提供,每個 View 控制視窗中的一個特定矩形區域並能回應使用者互動。Android 提供了大量預先定義的 View:

  • Widgets:提供可視化並可互動的元素,例如按鈕、輸入框、核取方塊或圖片。
  • Layouts:繼承自 ViewGroup 的 View,為它的子 View 提供特定的排列模型,例如線性佈局、表格佈局或相對佈局。

建立介面最常見的方式,是用 XML 佈局檔定義 View 並存進程式資源中,這樣可以將介面設計與定義行為的程式碼分離維護;接著用 setContentView() 傳入該佈局的資源 ID 即可。當然也可以在程式碼中動態 new 出 View,插入 ViewGroup 形成層次,最後把根 ViewGroup 傳給 setContentView()。

五、Bundle:Activity 之間的資料載體

Bundle 本質上是一個映射:從字串鍵到各種不同封裝類型的對應表。之所以是「封裝類型」而不是純數值類型,是因為它還需要能操作 Bundle 自身——Bundle 本身就是 Object 的子類,並非基本數值類型。在 Activity 之間傳遞資料時,實際被傳遞的就是 Bundle。

六、動手做:撥號介面

先建立 Java 檔案並在 onCreate 中設定佈局:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // 在這裡取得各 View 物件
}

輸入框的部分,關鍵屬性是 inputType="phone",它會讓鍵盤直接跳出數字鍵盤:

<EditText android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="phone" >
    <requestFocus />
</EditText>

幾個 Layout 與 R 檔案的重點:

  • match_parent 表示填滿父容器
  • <requestFocus /> 讓該控件在進入畫面時自動取得焦點、彈出軟鍵盤
  • android:id="@+id/button1" 會在 R 文件中產生對應的 ID 常數
  • findViewById(R.id.editText1) 用來取得該 ID 對應的 View 實例

而點擊事件在 Android 中有四種常見寫法:

1. 建立一個內部類實作 OnClickListener 接口,覆寫 onClick()。

2. 用匿名內部類直接實例化接口。

3. 讓 MainActivity 實作 OnClickListener 接口,在類別中覆寫 onClick(),再用 switch 分流。

4. 透過 XML 的 android:onClick 屬性,以反射機制調用 Activity 中同名的方法。

七、完整源碼

佈局檔 activity_main.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <EditText android:id="@+id/Phone_call"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:inputType="phone" >
        <requestFocus />
    </EditText>

    <Button android:id="@+id/Call_other"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/Phone_call"
        android:layout_below="@+id/Phone_call"
        android:layout_marginTop="16dp"
        android:text="Call_me" />

    <TextView android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/Call_other"
        android:layout_centerHorizontal="true"
        android:text="@string/_friend" />

    <Button android:id="@+id/Call_Chaibo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/Call_other"
        android:layout_alignLeft="@+id/Call_other"
        android:text="@string/call_caibo" />

    <!-- 其餘 Call_* 按鈕依此類推,以 layout_above 串成縱向鏈 -->
</RelativeLayout>

strings.xml(字串抽出是為了日後國際化,這是好習慣):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">MyFriend</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">MyFriend!</string>
    <string name="call_caibo">Call_柴博</string>
    <string name="call_wangqi">Call_王琪</string>
    <string name="call_jinrui">Call_靳瑞斌</string>
    <string name="call_ya">Call_廉亞偉</string>
    <string name="call_len">Call_冷正甫</string>
    <string name="call_ta">Call_唐濤</string>
    <string name="call_wan">Call_王琪</string>
    <string name="call_x">Call_相帥</string>
    <string name="_friend">"Friend."</string>
</resources>

MainActivity.java:

package com.example.myfriend;

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

public class MainActivity extends Activity implements OnClickListener {

    private String nummber = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button1 = (Button) findViewById(R.id.Call_other);
        Button button2 = (Button) findViewById(R.id.Call_Chaibo);
        Button button3 = (Button) findViewById(R.id.Call_chenyi);
        Button button4 = (Button) findViewById(R.id.Call_JINRUIBIN);
        Button button5 = (Button) findViewById(R.id.Call_lengzhenfu);
        Button button6 = (Button) findViewById(R.id.Call_linyawei);
        Button button7 = (Button) findViewById(R.id.Call_wangqi);
        Button button8 = (Button) findViewById(R.id.Call_xiangshuai);

        button1.setOnClickListener(MainActivity.this);
        button2.setOnClickListener(MainActivity.this);
        button3.setOnClickListener(MainActivity.this);
        button4.setOnClickListener(MainActivity.this);
        button5.setOnClickListener(MainActivity.this);
        button6.setOnClickListener(MainActivity.this);
        button7.setOnClickListener(MainActivity.this);
        button8.setOnClickListener(MainActivity.this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Call_other:
                EditText text = (EditText) findViewById(R.id.Phone_call);
                this.nummber = text.getText().toString();
                CallPhone(this.nummber);
                break;
            case R.id.Call_Chaibo:
                this.nummber = "656588";
                Toast.makeText(MainActivity.this, "柴博" + this.nummber, 0).show();
                CallPhone(this.nummber);
                break;
            case R.id.Call_wangqi:
                this.nummber = "652008";
                Toast.makeText(MainActivity.this, "王琪" + this.nummber, 0).show();
                CallPhone(this.nummber);
                break;
            // 其餘分支依此類推
            default:
                Toast.makeText(MainActivity.this, "ppp", 0).show();
        }
    }

    /** 以 Intent 觸發撥號 */
    private boolean CallPhone(String number) {
        if (TextUtils.isEmpty(nummber)) {
            Toast.makeText(MainActivity.this, "電話號碼不能為空!", 0).show();
            return false;
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + nummber));
        startActivity(intent);
        return true;
    }
}

這裡有個實務上必須知道的差別:Intent.ACTION_CALL 會直接撥出電話,因此必須在 AndroidManifest.xml 中申請 CALL_PHONE 權限,而且從 Android 6.0 開始還需要執行期動態授權。若只是想把號碼帶到撥號盤由使用者確認,改用 Intent.ACTION_DIAL 即可,它不需要任何權限,也更符合 Google Play 的規範——大多數情況下這才是更合適的選擇。

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