編輯:關於 Android 程式設計
用程式發簡訊是 Android 的經典入門練習,因為它同時涵蓋了權限申請、Intent、PendingIntent 與廣播接收四個觀念。本文從最基礎的版本開始,再補上發送狀態回呼,做成完整可用的樣子。
專案結構如下:

package cn.com.sms.send; import java.util.ArrayList; import java.util.Iterator; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Send extends Activity { private String message; private String number ; private EditText editText; private EditText editText2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); editText = (EditText) this.findViewById(R.id.number); editText2 = (EditText)this.findViewById(R.id.message); Button button = (Button)this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { number = editText.getText().toString(); message = editText2.getText().toString(); // 在LogCat中可以查看到number和message的相關信息 Log.i("number", number); Log.i("message", message); /*獲取系統默認的信息管理器,一定要注意的是SmsManager是android.telephony.SmsManager;這和 *我們使用的版本有關,在 Android 2.0 以前 應該使用 android.telephony.gsm.SmsManager *Android 2.0 之後的版本應該用 android.telephony.SmsManager。 */ SmsManager smsManager = SmsManager.getDefault(); /*PendingIntent.getBroadcast返回一個用於廣播的PendingIntent對象,類似於調用Content.sendBroadcast(); */ PendingIntent paIntent = PendingIntent.getBroadcast(Send.this, 0, new Intent("SMS_SENT"), 0); PendingIntent deliveryIntent = PendingIntent.getBroadcast(Send.this, 0, new Intent("SMS_DELIVERED"), 0); // smsManager.divideMessage有些時候短信如果超過了字數,我們就需要這個方法來幫我們拆分短信內容。 ArrayList<String> smses = smsManager.divideMessage(message); Iterator<String> iterator = smses.iterator(); while(iterator.hasNext()){ String temp = iterator.next(); //發送短信 smsManager.sendTextMessage(number, null, temp, paIntent, deliveryIntent); } // 彈出一個浮動框顯示提示內容,Toast.LENGTH_LONG代表浮動框顯示時間的長短 Toast.makeText(Send.this, "短信發送完成", Toast.LENGTH_LONG).show(); } }); } }
main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="歡迎使用短信發送器,請輸入電話號碼" /> <EditText android:id="@+id/number" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="這裡輸入電話號碼" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="歡迎使用短信發送器,請輸入短信內容" /> <EditText android:id="@+id/message" android:layout_width="fill_parent" android:layout_height="wrap_content" android:minLines="3" android:hint="這裡輸入短信內容" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="send" /> </LinearLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="cn.com.sms.send" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.SEND_SMS"></uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Send" 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>
執行結果:

跟打電話的小程式一樣,要完整測試功能需要開啟兩個 AVD,一個發送、一個接收。
核心類別是 SmsManager。取得方式:
SmsManager smsManager = SmsManager.getDefault();
sendTextMessage 的五個參數別搞混:
smsManager.sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent)
PendingIntent.getBroadcast() 的四個參數:
public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags)
divideMessage() 則是長短信的處理器:內容超過單則上限時,它會幫你切成多段,迴圈逐段送出即可。
權限別忘了宣告:
<uses-permission android:name="android.permission.SEND_SMS"/>
用兩個 AVD 模擬時,若出現 NO DNS servers found 而無法使用,通常是因為電腦沒有連網,跟程式本身無關。
直接發送(不等回報):
SmsManager smsMgr = SmsManager.getDefault(); smsMgr.sendTextMessage(address, null, message, null, null);
開啟系統的寫短信介面:
Uri smsToUri = Uri.parse("smsto://10086"); Intent mIntent = new Intent( android.content.Intent.ACTION_SENDTO, smsToUri ); startActivity( mIntent );
這種做法不發送任何訊息,只是把號碼帶進簡訊 App,也就不需要 SEND_SMS 權限,是正式 App 更常採用的方式。
分享檔案:
Intent i = new Intent(Intent.ACTION_SEND); i.putExtra(Intent.EXTRA_EMAIL, address); i.putExtra(Intent.EXTRA_SUBJECT, filename); i.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + filename)); i.setType("text/csv"); startActivity(Intent.createChooser(i, "EMail File"));
基礎版的問題是「發送完成」這個 Toast 只代表程式跑完了,不代表簡訊真的送出去。要拿到真實結果,必須註冊廣播接收者:
package cn.com.sms.send; import java.util.ArrayList; import java.util.Iterator; 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.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Send extends Activity { private String message; private String number ; private EditText editText; private EditText editText2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); editText = (EditText) this.findViewById(R.id.number); editText2 = (EditText)this.findViewById(R.id.message); Button button = (Button)this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { number = editText.getText().toString(); message = editText2.getText().toString(); // 在LogCat中可以查看到number和message的相關信息 Log.i("number", number); Log.i("message", message); /*獲取系統默認的信息管理器,一定要注意的是SmsManager是android.telephony.SmsManager;這和 *我們使用的版本有關,在 Android 2.0 以前 應該使用 android.telephony.gsm.SmsManager *Android 2.0 之後的版本應該用 android.telephony.SmsManager。 */ SmsManager smsManager = SmsManager.getDefault(); /*PendingIntent.getBroadcast返回一個用於廣播的PendingIntent對象,類似於調用Content.sendBroadcast(); */ PendingIntent paIntent = PendingIntent.getBroadcast(Send.this, 0, new Intent("SMS_SENT2"), 0); PendingIntent deliveryIntent = PendingIntent.getBroadcast(Send.this, 0, new Intent("SMS_DELIVERED2"), 0); // 注冊一個BroadcastReceiver,當有匹配它的IntentFilter的Intent出現時,該方法會被觸發 registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { int resultCode = getResultCode(); switch(resultCode){ case Activity.RESULT_OK: Toast.makeText(getBaseContext(), "信息發送成功了哦、", Toast.LENGTH_LONG).show(); break; default: Toast.makeText(getBaseContext(), "信息發送失敗了哦、", Toast.LENGTH_LONG).show(); } } }, new IntentFilter("SMS_SENT2")); registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(getBaseContext(), "deliveryIntent", Toast.LENGTH_LONG).show(); Log.i("短信接收人是否查看信息", "看了"); } }, new IntentFilter("SMS_DELIVERED2")); // smsManager.divideMessage有些時候短信如果超過了字數,我們就需要這個方法來幫我們拆分短信內容。 ArrayList<String> smses = smsManager.divideMessage(message); Iterator<String> iterator = smses.iterator(); while(iterator.hasNext()){ String temp = iterator.next(); //發送短信 smsManager.sendTextMessage(number, null, temp, paIntent, deliveryIntent); } // 彈出一個浮動框顯示提示內容,Toast.LENGTH_LONG代表浮動框顯示時間的長短 Toast.makeText(Send.this, "短信發送完成", Toast.LENGTH_LONG).show(); } }); } }
main.xml 與 AndroidManifest.xml 與前面相同。
registerReceiver() 在 Context 中的定義是:
public abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter);
系統查詢到符合 filter 的廣播時,就會交給該 receiver 於 onReceive() 中處理。發送狀態的判斷靠 getResultCode():回傳 Activity.RESULT_OK 代表成功,其他值代表各種失敗原因。
若不透過程式碼動態註冊,也可以在清單檔宣告:
<receiver android:name="類名"> <intent-filter> <action android:name="接收者中Intent參數的action屬性" /> </intent-filter> </receiver>
注意 receiver 標籤與 activity 標籤是平級的,都要放在 application 底下。
動態註冊記得反註冊。範例中在 onClick 裡註冊接收者,每按一次按鈕就多一組,且 Activity 銷毀後仍殘留,會造成記憶體洩漏與重複回呼。正確做法是在 onCreate 註冊、onDestroy 呼叫 unregisterReceiver(),或改用短命的物件生命週期管理。
Android 4.4 之後的變化。從 API 19 起,非預設簡訊 App 傳送簡訊的途徑被限制,sendTextMessage 仍可用但行為受約束;Android 6.0 起 SEND_SMS 屬於執行期危險權限,必須動態請求,只寫在清單檔會直接拋 SecurityException。若你的 App 不是使用者的預設簡訊程式,正式上線前務必確認政策規範。
模擬器中文亂碼。在模擬器之間互傳中文,接收端可能出現亂碼;真機上則不會有這個問題,因此不需要自己做編碼轉換。
總結一下:發簡訊的技術門檻不高,真正需要花心思的是權限、生命週期與失敗情境的處理。把這幾塊補齊,功能才算真正可靠。
Android 消息機制 Handler 深度解析(源碼 + Demo)
Handler 是開發人員在面試中最常見的問題之一。本文將從源碼層與使用方法兩個角度,較為全面地解讀 Handler 這套機制。 一、什麼是 Handler Handl
Android AsyncTask 與 Handler 用法實例全面分析
本文全面分析 Android 中 AsyncTask 與 Handler 的用法,供大家參考。 首先,我們得釐清一個概念:什麼是 UI 執行緒?顧名思義,UI 執行緒就是
一個手機號能註冊兩個微信嗎 解法圖解
一個手機號可以註冊兩個微信嗎?很多人還不知道具體做法,小編下面就分享完整思路。 一個手機號怎麼註冊兩個微信 登入你(已綁定手機號)的微信,點擊右上角的「┇」圖標。 在彈
OpenCV 使用 Harris 演算法實作角點檢測
效果展示 下面先觀察 Harris 角點檢測在圖像上的實際輸出。角點通常會以圓點標記,越明顯的交會區域,響應值越高。 什麼是 Harris 角點檢測 角點可以理解為兩