android发送短信以及监听发送状态


 自定义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);




 

你可能感兴趣的:(exception,android,String,null,action,sms)