jollen.org

Jollen 的 Blog
Jollen's email: jollen # jollen.org
more:  Jollen's Training

Jollen 的 Android 教學,#27: 使用ACTION_CALL實作自動撥號: HelloIntentDialer

.作者:jollen/
.日期:August 7, 2009 11:25 AM


HelloIntentDialer是一個自動撥號程式,執行時會自動撥號到指定的電話。這樣的程式要怎麼寫呢?先看到HelloIntentDialer.java的完整程式如下:

package com.moko.hellointentdialer;
 
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
 
public class HelloIntentDialer extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        Intent dial = new Intent();
        dial.setAction("android.intent.action.CALL");
        dial.setData(Uri.parse("tel:119"));
        startActivity(dial);        
    }
}

因為permission的關係,所以也要在AndroidManifest.xml裡加上「CALL_PHONE」的權限。AndroidManifest.xml的完整內容如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.moko.hellointentdialer"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".HelloIntentDialer"
                  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="3" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
</manifest>>

這個範例相當簡單,但足以說明Intent的核心精神了。程式說明:

1. 先產生一個Intent物件:

 Intent dial = new Intent();

2. 設定Intent的action為「android.intent.action.CALL」,這是一個內建的action:

 dial.setAction("android.intent.action.CALL");

內建action「CALL」需要附帶一筆資料,而資料的寫法是使用URI格式:

 dial.setData(Uri.parse("tel:119"));

4. 「CALL」是一個activity action,所以呼叫startActivity()向Intent送給框架:

 startActivity(dial);

這個範例的概念並不難,「送出一個帶有內建action的Intent給框架,因為action為CALL,所以框架會去啟動撥號activity並打電話。」

Tags:

純手工打造說明:技術專欄文章為 Jollen 原創,內容皆為人工撰寫,無 AI 生成。轉載請註明出處與作者,並全文引用。轉載時請在文章開頭或結尾明顯處註明「本文出處:https://www.jollen.org,已取得原作者同意並授權使用。」
訂閱電子報:不定期 Jollen's Blog 精選文章隨 Moko365 電子報寄送;請透過 Moko365 電子報訂閱(可隨時取消)。

Copyright(c) 2001–2009 www.jollen.org. All rights reserved.
Last update: 2026-07-22