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

Android 收發短信實作:廣播接收與 SmsManager

編輯:關於 Android 程式設計

每一部手機都具備短信收發能力,在 Android 上分別靠「攔截系統廣播」與「SmsManager」來完成。以下分兩部分實作。

一、接收短信

整體步驟:

  1. 建立內部廣播接收器,接收系統發出的短信廣播
  2. 從收到的內容中解析出發送者與短信正文
  3. 在 Activity 中註冊廣播
  4. 加入接收短信的權限

布局用來顯示發送者號碼與內容:

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

    <TextView android:id="@+id/sms_from"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:text="From" />
    <TextView android:id="@+id/sms_from_txt"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@id/sms_from"/>

    <TextView android:id="@+id/sms_content"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_below="@id/sms_from"
        android:layout_marginTop="20dp"
        android:text="Content" />
    <TextView android:id="@+id/sms_content_txt"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="20dp"
        android:layout_below="@id/sms_from_txt"
        android:layout_toRightOf="@id/sms_content"/>
</RelativeLayout>
 public class MainActivity extends AppCompatActivity {

    private TextView fromTv;
    private TextView contentTv;
    private IntentFilter intentFilter;
    private MessageReceiver messageReceiver;

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

    private void getSms() {
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        messageReceiver = new MessageReceiver();
        // 設置較高的優先級
        intentFilter.setPriority(100);
        registerReceiver(messageReceiver, intentFilter);
    }

    private void initView() {
        fromTv = (TextView) findViewById(R.id.sms_from_txt);
        contentTv = (TextView) findViewById(R.id.sms_content_txt);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(messageReceiver);
    }

    class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            // 提取短信消息
            Object[] pdus = (Object[]) bundle.get("pdus");
            SmsMessage[] messages = new SmsMessage[pdus.length];
            for (int i = 0; i < messages.length; i++) {
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            }
            // 獲取發送方號碼
            String address = messages[0].getOriginatingAddress();
            String fullMessage = "";
            for (SmsMessage message : messages) {
                // 拼接短信內容
                fullMessage += message.getMessageBody();
            }
            // 截斷廣播
            abortBroadcast();
            fromTv.setText(address);
            contentTv.setText(fullMessage);
        }
    }
}

兩個重點:註冊的廣播接收器必須在 onDestroy() 中取消註冊,否則會造成記憶體洩漏與重複接收。

另外,短信廣播是有序廣播,因此接收器的優先級與 abortBroadcast() 的組合決定了「誰先看到這則短信」。要不要截斷,取決於你的應用是否要取代系統簡訊程式的角色——這是一個會直接影響使用者體驗的決定,不建議在一般應用中隨意截斷。

二、發送短信

步驟:

  1. 取得接收者號碼與短信內容
  2. 取得短信發送管理實例
  3. 構造 PendingIntent 以監控發送狀態
  4. 呼叫發送方法並傳入參數
  5. 建立廣播接收器內部類接收發送結果
  6. 註冊廣播接收器
  7. 在 onDestroy() 中取消註冊
  8. 在 manifest 中加入發送權限
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText android:id="@+id/to_ed"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="to"/>
    <EditText android:id="@+id/to_content"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@id/to_ed"
        android:hint="content"/>
    <Button android:id="@+id/send_msg"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@id/to_content"
        android:text="@string/send_message"/>
</RelativeLayout>
 public class SendMsgActivity extends AppCompatActivity implements View.OnClickListener {

    private Context context;
    private EditText toEdit;
    private EditText toContent;
    private IntentFilter sendFilter;
    private SendStatusReceiver sendStatusReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_msg);
        context = this;
        initView();
    }

    private void initView() {
        toEdit = (EditText) findViewById(R.id.to_ed);
        toContent = (EditText) findViewById(R.id.to_content);
        Button sendMsg = (Button) findViewById(R.id.send_msg);
        sendMsg.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_msg:
                sendMessage();
                break;
            default:
                break;
        }
    }

    private void sendMessage() {
        String to = toEdit.getText().toString();
        String content = toContent.getText().toString();

        // 獲得廣播接收器實例和 IntentFilter 實例
        sendStatusReceiver = new SendStatusReceiver();
        sendFilter = new IntentFilter();
        sendFilter.addAction("SENT_SMS_ACTION");
        registerReceiver(sendStatusReceiver, sendFilter);

        // 構造 PendingIntent 啟動短信發送狀態監控廣播
        Intent sendIntent = new Intent("SENT_SMS_ACTION");
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, sendIntent, 0);

        // 獲得短信管理實例並發送
        // 參數依次為:接收者號碼、serviceCenterAddress、短信內容、發送結果 PendingIntent、送達結果 PendingIntent
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(to, null, content, pi, null);
    }

    /** 監控短信是否發送成功 */
    class SendStatusReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (getResultCode() == RESULT_OK) {
                Toast.makeText(context, "successful", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "failed", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(sendStatusReceiver);
    }
}

權限宣告:

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

三、實務上必須知道的限制

權限與上架政策。SEND_SMS 與 RECEIVE_SMS 都屬於高風險權限。若你的應用不是「預設短信處理程式」,在 Google Play 上申請這類權限會被要求提交嚴格說明,多數情況會被駁回。請先確認產品定位是否真的需要,否則應改用系統的 ACTION_SENDTO 把編輯工作交給簡訊 App。

長短信要分段。sendTextMessage() 單次有長度上限,超出時應先用 smsManager.divideMessage(content) 切段後逐段發送,並自行處理收端的拼接順序。

發送結果要抽屜化判斷。getResultCode() 回傳 RESULT_OK 只代表「已交給電信網路」,不代表對方收到。送達確認要另外監聽 sendTextMessage() 的第五個參數(deliveredIntent)。

Android 6.0 以上要動態申請。僅在 manifest 宣告已不足夠,執行期必須透過 requestPermissions() 取得使用者同意,並處理被拒絕的情況。

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