自定义ACTION常数,作为广播的Intent Filter识别常数
1.private String SMS_SEND_ACTIOIN = "SMS_SEND_ACTIOIN";
2.private String SMS_DELIVERED_ACTION = "SMS_DELIVERED_ACTION"; 其中,SMS_SEND_ACTIOIN 为发送成功接收到的回复;SMS_DELIVERED_ACTION 是短信接受者接受到短信的回复;
根据运营商的不同,SMS_DELIVERED_ACTION 回复与否也不同。可以亲自试验下。
自定义mServiceReceiver覆盖BroadcastReceiver聆听短信状态信息
1.public class MyServiceReceiver extends BroadcastReceiver {
2. @Override 3. public void onReceive(Context context, Intent intent) { 4. // TODO Auto-generated method stub 5. try { 6. /* Android.content.BroadcastReceiver.getResultCode()方法 */ 7. switch (getResultCode()) { 8. case Activity.RESULT_OK: 9. /* 发送短信成功 */ 10. Log.d("lmn", sendNums 11. + "----发送短信成功---------------------------"); 12. break; 13. case SmsManager.RESULT_ERROR_GENERIC_FAILURE: 14. /* 发送短信失败 */ 15. case SmsManager.RESULT_ERROR_RADIO_OFF: 16. case SmsManager.RESULT_ERROR_NULL_PDU: 17. default: 18. Log.d("lmn", sendNums 19. + "----发送短信失败---------------------------"); 20. break; 21. }
22. } catch (Exception e) { 23. e.getStackTrace();
24. }
25. }
26. }
在oncreate中注册广播事件:
1./* 自定义IntentFilter为SENT_SMS_ACTIOIN Receiver */
2.IntentFilter mFilter01;
3.mFilter01 = new IntentFilter(SMS_SEND_ACTIOIN); 4.mReceiver01 = new MyServiceReceiver(); 5.registerReceiver(mReceiver01, mFilter01);
6.
7./* 自定义IntentFilter为DELIVERED_SMS_ACTION Receiver */ 8.mFilter01 = new IntentFilter(SMS_DELIVERED_ACTION); 9.mReceiver02 = new MyServiceReceiver(); 10.registerReceiver(mReceiver02, mFilter01);
同时在 onDestroy 中取消:
1./* 取消注册自定义Receiver */
2. if (mReceiver01 != null && mReceiver02 != null) { 3. unregisterReceiver(mReceiver01);
4. unregisterReceiver(mReceiver02);
5. }
发送短信:
1.SmsManager smsManager = SmsManager.getDefault();
1./* 创建自定义Action常数的Intent(给PendingIntent参数之用) */
2.Intent itSend = new Intent(SMS_SEND_ACTIOIN); 3.itSend.putExtras(b);
4./* sentIntent参数为传送后接受的广播信息PendingIntent */ 5.PendingIntent mSendPI = PendingIntent.getBroadcast(
6.getApplicationContext(),
7.(int) System.currentTimeMillis(), itSend, 8.PendingIntent.FLAG_UPDATE_CURRENT);
1.Intent itDeliver = new Intent(SMS_DELIVERED_ACTION);
1.itDeliver.putExtras(b);
1./* deliveryIntent参数为送达后接受的广播信息PendingIntent */
2.PendingIntent mDeliverPI = PendingIntent.getBroadcast(
3.getApplicationContext(),
4.(int) System.currentTimeMillis(), itDeliver, 5.PendingIntent.FLAG_UPDATE_CURRENT);
6.// 发送短信
1.smsManager.sendTextMessage(sendNum, null, strMessage,
2.mSendPI, mDeliverPI
本篇文章来源于 Linux公社网站(www.linuxidc.com) 原文链接:http://www.linuxidc.com/Linux/2011-10/46071.htm