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

Android 短信收发實作:BroadcastReceiver 攔截簡訊與發送狀態回呼

編輯:關於 Android 程式設計

短信的接收處理已有不少成熟應用,最典型的就是驗證碼自動填寫——手機收到驗證碼簡訊後,App 直接攔下內容並跳過輸入步驟。至於發送,API 本身很直白,難點反而在於「怎麼知道到底發出去沒有」。本文用一個小範例把兩件事一起做完。

效果:

MainActivity

 import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private TextView sender; private TextView content; private IntentFilter receiveFilter; private MessageReceiver messageReceiver; private EditText to; private EditText msgInput; private Button send; private IntentFilter sendFilter; private SendStatusReceiver sendStatusReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sender = (TextView) findViewById(R.id.sender); content = (TextView) findViewById(R.id.content); to = (EditText) findViewById(R.id.to); msgInput = (EditText) findViewById(R.id.msg_input); send = (Button) findViewById(R.id.send); //為接收短信設置要監聽的廣播 receiveFilter = new IntentFilter(); receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); messageReceiver = new MessageReceiver(); registerReceiver(messageReceiver, receiveFilter); //為發送短信設置要監聽的廣播 sendFilter = new IntentFilter(); sendFilter.addAction("SENT_SMS_ACTION"); sendStatusReceiver = new SendStatusReceiver(); registerReceiver(sendStatusReceiver, sendFilter); send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //發送短信 //並使用sendTextMessage的第四個參數對短信的發送狀態進行監控 SmsManager smsManager = SmsManager.getDefault(); Intent sentIntent = new Intent("SENT_SMS_ACTION"); PendingIntent pi = PendingIntent.getBroadcast( MainActivity.this, 0, sentIntent, 0); smsManager.sendTextMessage(to.getText().toString(), null, msgInput.getText().toString(), pi, null); } }); } @Override protected void onDestroy() { super.onDestroy(); //在Activity摧毀的時候停止監聽 unregisterReceiver(messageReceiver); unregisterReceiver(sendStatusReceiver); } class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); //使用pdu秘鑰來提取一個pdus數組 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(); } sender.setText(address); content.setText(fullMessage); } } class SendStatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (getResultCode() == RESULT_OK) { //發送成功 Toast.makeText(context, "Send succeeded", Toast.LENGTH_LONG) .show(); } else { //發送失敗 Toast.makeText(context, "Send failed", Toast.LENGTH_LONG) .show(); } } } } 

activity_main 版面

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="From:" /> <TextView android:id="@+id/sender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="Content:" /> <TextView android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="To:" /> <EditText android:id="@+id/to" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <EditText android:id="@+id/msg_input" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1" /> <Button android:id="@+id/send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="Send" /> </LinearLayout> </LinearLayout> 

AndroidManifest

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.smstest" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" /> //接受短信 <uses-permission android:name="android.permission.RECEIVE_SMS" /> //發送短信 <uses-permission android:name="android.permission.SEND_SMS" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.smstest.MainActivity" 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> 

幾個實作要點

接收端:攔的是 android.provider.Telephony.SMS_RECEIVED 這個系統廣播,資料放在名為 pdus 的陣列裡,且長短信會被拆成多筆,因此範例才要遍歷 SmsMessage 把 body 拼接起來,否則只會拿到片段。

發送端:sendTextMessage() 的第四個參數是一個 PendingIntent,簡訊送達後系統會回呼它,再由 SendStatusReceiver 透過 getResultCode() 判斷成功或失敗。這也是為什麼要額外註冊一個自訂 action 的廣播接收器。

別忘了:onDestroy 中必須 unregisterReceiver,否則會洩漏接收器並導致 Activity 無法回收。另外 Android 4.4 以上若要攔截簡訊,接收器需具備較高優先權;6.0 以上則一律要動態申請 RECEIVE_SMS 與 SEND_SMS 權限。

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