短信收發在應用中我們也經常會用到,特別是短信的發送。
那麼,在android中如何實現呢?
短信發送
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(sendPhone.getText().toString(), null, sendText.getText().toString(), null, null);
這兩句代碼就實現了短信的發送,當然,你要在AndroidManifest.xml中添加上權限,允許發送短信: <uses-permission android:name="android.permission.SEND_SMS"/>
短信的發送的核心代碼就是這些。destinationAddress: the address to send the message to
scAddress: is the service center address or null to use the current default SMSC
text : the body of the message to send
sentIntent: if not NULL this PendingIntent is broadcast when the message is successfully sent, or failed. The result code will be Activity.RESULT_OK for success, or one of these errors:
RESULT_ERROR_GENERIC_FAILURE
RESULT_ERROR_RADIO_OFF
RESULT_ERROR_NULL_PDU
For RESULT_ERROR_GENERIC_FAILURE the sentIntent may include the extra "errorCode" containing a radio technology specific value, generally only useful for troubleshooting.
The per-application based SMS control checks sentIntent. If sentIntent is NULL the caller will be checked against all unknown applications, which cause smaller number of SMS to be sent in checking period.
deliveryIntent: if not NULL this PendingIntent is broadcast when the message is delivered to the recipient. The raw pdu of the status report is in the extended data ("pdu").
以上是API中對它們的解釋,簡單點翻譯,如下:destinationAddress:目標的電話號碼;
<pre name="code" class="html">scAddress:短信服務中心,如果寫null,就用當前默認的服務中心;
<pre name="code" class="html">text :短信內容;
<pre name="code" class="html">sentIntent:這是一個pendingintent,用於監聽短信的發送狀態;
deliveryIntent:<span style="font-family: Arial, Helvetica, sans-serif;">這是一個pendingintent,用於監聽短信的被接收狀態;</span>
PendingIntent pIntent=PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(sendFlag), 0);
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(sendPhone.getText().toString(), null, sendText.getText().toString(), pIntent, null);
其中,sendFlag爲:String sendFlag="SENT_SMS_ACTION";
這樣就可以在廣播BroadcastReceiver的onReceive方法中監聽是否短信發送成功。還有一個監聽短信是否成功被接收,你也可以在源碼的基礎上添加,廣播過濾是 "DELIVERED_SMS_ACTION"。
短信接收
短信的接收,用到的就是廣播。監聽系統廣播"android.provider.Telephony.SMS_RECEIVED",當收到該廣播時,解析該廣播帶的數據。這就是短信信息。以下是短信接收的核心解析代碼:
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(receiverFlag.equals(intent.getAction()))
{
if(getResultCode()==RESULT_OK)
{
Bundle bundle=intent.getExtras();
Object[] objects=(Object[])bundle.get("pdus");
SmsMessage[] smsMessages=new SmsMessage[objects.length];
for(int i=0;i<objects.length;i++)
{
smsMessages[i]=SmsMessage.createFromPdu((byte[])objects[i]);
}
String phoneString="來信號碼:";
String contentString="來信信息:";
for (SmsMessage smsMessage : smsMessages) {
phoneString=smsMessage.getDisplayOriginatingAddress();
contentString+=smsMessage.getDisplayMessageBody();
}
recevicePhone.setText(phoneString);
receviceText.setText(contentString);
}
步驟如下:取廣播附帶信息-》取其中key爲“pdus”-》轉爲object[]類型,存儲數據-》新建短信數組,並將object[i]值賦值給短信數組-》在短信數組中取出號碼和串聯在一起的短信數據。