二、 sms發送 與短訊息發送相關的類為:SmsManager.
Java代碼 SmsManager.sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
參數說明:
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 sucessfully 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. 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").
其中兩個PendingIntent模式為:
Java代碼 PendingIntent sentIntent = PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0); Intent deliveryIntent = PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);
並註冊接收器,根據getResultCode()來判斷:
Java代碼 registerReceiver(sendReceiver); registerReceiver(deliveredReceiver);
三、 sms接收 根據接收時廣播的android.provider.Telephony.SMS_RECEIVED的Intent.我們可以擴充一個BroadcastReceiver來接收sms.
傳遞的Intent包含pdus資料。相關代碼如下:
Java代碼 Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); SmsMessage[] msgs = new SmsMessage[pdus.length]; for (int i = 0; i < pdus.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); }
四、 採用ContentObserver監控簡訊資料庫 上面方法三中並不能對sms進行更新和刪除操作,要做這些操作需要用ContentObserver來監控簡訊資料庫的變化來進行相關操作。
1. 簡訊資料庫的ContentUri
Java代碼 public final static String SMS_URI_ALL = "content://sms/"; //0 public final static String SMS_URI_INBOX = "content://sms/inbox";//1 public final static String SMS_URI_SEND = "content://sms/sent";//2 public final static String SMS_URI_DRAFT = "content://sms/draft";//3 public final static String SMS_URI_OUTBOX = "content://sms/outbox";//4 public final static String SMS_URI_FAILED = "content://sms/failed";//5 public final static String SMS_URI_QUEUED = "content://sms/queued";//6
2. sms主要結構:
Java代碼 _id => 短訊息序號 如100 thread_id => 對話的序號 如100 address => 寄件者地址,手機號.如+8613811810000 person => 寄件者,返回一個數字就是連絡人清單裡的序號,陌生人為null date => 日期 long型。如1256539465022