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

Android 學習筆記:模擬發送簡訊的完整實作

編輯:關於 Android 程式設計

寄送簡訊是 Android 相當早期的特色能力之一,透過 SmsManager 幾行程式碼就能完成。以下以 Android 2.2 模擬器為環境,示範一個包含號碼輸入、內容輸入與寄送按鈕的完整範例。

一、字串資源 string.xml

把介面上出現的文字抽到資源檔是好習慣,後續要改文案或做多語系都方便得多。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, SmsActivity!</string>
    <string name="app_name">簡訊發送器</string>
    <string name="mobile">請輸入手機號</string>
    <string name="content">請輸入簡訊內容</string>
    <string name="button">發送簡訊</string>
    <string name="success">發送成功</string>
</resources>

二、版面配置 main.xml

用垂直排列的 LinearLayout 依序放:提示文字、號碼輸入框、內容輸入框(設為三行高)、發送按鈕。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

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

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

    <EditText
        android:id="@+id/mobile"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

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

    <EditText
        android:id="@+id/content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minLines="3" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button" />
</LinearLayout>

三、Activity 程式碼

核心邏輯只有三步:取得系統的 SmsManager、把長訊息切分成符合單則上限的片段、逐則送出。

package com.android.sms;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SmsActivity extends Activity {

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

        Button btn = (Button) this.findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                EditText mobileText = (EditText) findViewById(R.id.mobile);
                EditText contentText = (EditText) findViewById(R.id.content);

                // 取得手機號與簡訊內容
                String mobile = mobileText.getText().toString();
                String content = contentText.getText().toString();

                // 取得系統的簡訊管理器
                SmsManager sm = SmsManager.getDefault();

                // 超過單則容量時自動拆分為多則
                List<String> texts = sm.divideMessage(content);
                for (String text : texts) {
                    sm.sendTextMessage(mobile, null, text, null, null);
                }

                // 提示發送結果
                Toast.makeText(SmsActivity.this, R.string.success,
                        Toast.LENGTH_LONG).show();
            }
        });
    }
}

為什麼要呼叫 divideMessage 而不是直接送?因為單則簡訊有長度上限(純文字約 160 字元,中文編碼下更少)。直接送出過長的內容會失敗,而 divideMessage 會依編碼自動計算並切成多段,再由迴圈逐則寄出。

四、加入發送簡訊的權限

這是最容易被遺漏的一步。沒有 SEND_SMS 權限,程式會在執行時直接拋出安全性例外。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.android.sms"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.SEND_SMS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SmsActivity"
            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>
</manifest>

五、補充說明

  • sendTextMessage 的五個參數依序是:收件號碼、發件中心號碼(一般傳 null)、內容、寄送結果的 PendingIntent、送達通知的 PendingIntent。範例中後兩者傳 null,代表不接收狀態回呼。
  • 若需要知道簡訊是否真的送達,就必須建立 PendingIntent 並註冊廣播接收器,在 onReceive 中依 getResultCode() 判斷成功或失敗。
  • 在模擬器上測試時,收件號碼可以填另一個模擬器的號碼(預設為 5554),兩端要在同一個 AVD 群組中才能互送。
  • 從 Android 4.4 開始,官方建議改用 SmsManager.getDefault() 以外的 SMS Dispatcher 方式,並在 Android 6.0 之後需要執行期動態請求 SEND_SMS 權限,不能只在清單中宣告。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved