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

Android 發送短信並即時得知發送結果的完整教學

編輯:關於 Android 開發

發短信同時掌握送達狀態

用 SmsManager 發送短信時,我們往往希望能知道「是否發送成功」以及「對方是否已接收」。好消息是:無論發送結果如何,系統都會發送廣播,我們只要註冊兩個廣播接收器去監聽即可。

整体思路:

1. 加上發送短信的權限;

2. 發送時傳入兩個 PendingIntent,一個用來回報「發送結果」,一個用來回報「對方接收」;

3. 註冊廣播接收器,根據 getResultCode() 判斷狀態;

4. 佈局很簡單,兩個 EditText(號碼、內容)加一個按鈕。

一、發送結果廣播 MySmsSendReceiver

package com.example.fanlei.cutnotedemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.widget.Toast;

public class MySmsSendReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("SMS_SEND")) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(context, "發送成功", Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(context, "發送失敗", Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                case SmsManager.RESULT_ERROR_NULL_PDU:
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    break;
            }
        }
    }
}

二、對方接收廣播 MySmsDeliverReceiver

package com.example.fanlei.cutnotedemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MySmsDeliverReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("SMS_DELIVER")) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(context, "對方已接收", Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    break;
            }
        }
    }
}

三、主程式 MainActivity

記得在清單檔加上 SEND_SMS 權限。發送時,若內容超過 70 字,要用 divideMessage() 拆分後逐條發送:

package com.example.fanlei.cutnotedemo;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.List;

public class MainActivity extends ActionBarActivity {
    private EditText editText1, editText2;
    private MySmsSendReceiver mySmsSendReceiver;
    private MySmsDeliverReceiver mySmsDeliverReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mySmsSendReceiver = new MySmsSendReceiver();
        mySmsDeliverReceiver = new MySmsDeliverReceiver();
        editText1 = (EditText) findViewById(R.id.editText1); // 手機號
        editText2 = (EditText) findViewById(R.id.editText2); // 內容

        Intent sendIntent = new Intent();
        sendIntent.setAction("SMS_SEND");
        Intent deliverIntent = new Intent();
        deliverIntent.setAction("SMS_DELIVER");
        final PendingIntent send = PendingIntent.getBroadcast(this, 0, sendIntent, 0);
        final PendingIntent deliver = PendingIntent.getBroadcast(this, 0, deliverIntent, 0);

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNumber = editText1.getText().toString();
                String content = editText2.getText().toString();
                if (phoneNumber.equals("")) {
                    Toast.makeText(MainActivity.this, "手機號碼為空", Toast.LENGTH_SHORT).show();
                } else {
                    SmsManager sm = SmsManager.getDefault();
                    if (content.length() > 70) {
                        List<String> contents = sm.divideMessage(content);
                        for (String sms : contents) {
                            sm.sendTextMessage(phoneNumber, null, sms, send, deliver);
                        }
                    } else {
                        sm.sendTextMessage(phoneNumber, null, content, send, deliver);
                    }
                }
            }
        });

        registerReceiver(mySmsSendReceiver, new IntentFilter("SMS_SEND"));
        registerReceiver(mySmsDeliverReceiver, new IntentFilter("SMS_DELIVER"));
    }
}

四、佈局 activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1"
        android:hint="手機號"
        android:inputType="phone" />
    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:hint="內容" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:text="發送短信" />
</RelativeLayout>

測試時可以傳給 10086 之類的號碼驗證。透過兩組 PendingIntent 與廣播,就能清楚掌握短信的發送與送達狀態,讓應用更具互動性。

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