自定義ACTION常數,作為廣播的Intent Filter識別常數
- private String SMS_SEND_ACTIOIN = "SMS_SEND_ACTIOIN";
- private String SMS_DELIVERED_ACTION = "SMS_DELIVERED_ACTION";
其中,SMS_SEND_ACTIOIN 為發送成功接收到的回復;SMS_DELIVERED_ACTION 是短信接受者接受到短信的回復;
根據運營商的不同,SMS_DELIVERED_ACTION 回復與否也不同。可以親自試驗下。
自定義mServiceReceiver覆蓋BroadcastReceiver聆聽短信狀態信息
- public class MyServiceReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- // TODO Auto-generated method stub
- try {
- /* Android.content.BroadcastReceiver.getResultCode()方法 */
- switch (getResultCode()) {
- case Activity.RESULT_OK:
- /* 發送短信成功 */
- Log.d("lmn", sendNums
- + "----發送短信成功---------------------------");
- break;
- case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
- /* 發送短信失敗 */
- case SmsManager.RESULT_ERROR_RADIO_OFF:
- case SmsManager.RESULT_ERROR_NULL_PDU:
- default:
- Log.d("lmn", sendNums
- + "----發送短信失敗---------------------------");
- break;
- }
- } catch (Exception e) {
- e.getStackTrace();
- }
- }
- }
在oncreate中注冊廣播事件:
- /* 自定義IntentFilter為SENT_SMS_ACTIOIN Receiver */
- IntentFilter mFilter01;
- mFilter01 = new IntentFilter(SMS_SEND_ACTIOIN);
- mReceiver01 = new MyServiceReceiver();
- registerReceiver(mReceiver01, mFilter01);
-
- /* 自定義IntentFilter為DELIVERED_SMS_ACTION Receiver */
- mFilter01 = new IntentFilter(SMS_DELIVERED_ACTION);
- mReceiver02 = new MyServiceReceiver();
- registerReceiver(mReceiver02, mFilter01);
同時在 onDestroy 中取消:
- /* 取消注冊自定義Receiver */
- if (mReceiver01 != null && mReceiver02 != null) {
- unregisterReceiver(mReceiver01);
- unregisterReceiver(mReceiver02);
- }
發送短信:
- SmsManager smsManager = SmsManager.getDefault();
- /* 創建自定義Action常數的Intent(給PendingIntent參數之用) */
- Intent itSend = new Intent(SMS_SEND_ACTIOIN);
- itSend.putExtras(b);
- /* sentIntent參數為傳送後接受的廣播信息PendingIntent */
- PendingIntent mSendPI = PendingIntent.getBroadcast(
- getApplicationContext(),
- (int) System.currentTimeMillis(), itSend,
- PendingIntent.FLAG_UPDATE_CURRENT);
- Intent itDeliver = new Intent(SMS_DELIVERED_ACTION);
- itDeliver.putExtras(b);
- /* deliveryIntent參數為送達後接受的廣播信息PendingIntent */
- PendingIntent mDeliverPI = PendingIntent.getBroadcast(
- getApplicationContext(),
- (int) System.currentTimeMillis(), itDeliver,
- PendingIntent.FLAG_UPDATE_CURRENT);
- // 發送短信
- smsManager.sendTextMessage(sendNum, null, strMessage,
- mSendPI, mDeliverPI);