Profile image for Wei Wang aztack
send sms in android2.2 and display status
Language
Java
Tags
android java sms
Favorited By
Profile image for Wei Wang

Send SMS

1 public class AppActivity extends Activity { 2 3 private void setStatus(String text) 4 { 5 TextView status = (TextView)findViewById(R.id.status); 6 status.setText(text); 7 } 8 9 private void sendSMS(String phoneNumber, String message) 10 { 11 String SENT = "SMS_SENT"; 12 String DELIVERED = "SMS_DELIVERED"; 13 14 PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, 15 new Intent(SENT), 0); 16 17 PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, 18 new Intent(DELIVERED), 0); 19 20 //---when the SMS has been sent--- 21 BroadcastReceiver br = new BroadcastReceiver(){ 22 @Override 23 public void onReceive(Context arg0, Intent arg1) { 24 switch (getResultCode()) 25 { 26 case Activity.RESULT_OK: 27 setStatus("短信已发送"); 28 break; 29 case SmsManager.RESULT_ERROR_GENERIC_FAILURE: 30 setStatus("发送失败"); 31 break; 32 case SmsManager.RESULT_ERROR_NO_SERVICE: 33 setStatus("不在服务区"); 34 break; 35 case SmsManager.RESULT_ERROR_NULL_PDU: 36 setStatus("Null PDU"); 37 break; 38 case SmsManager.RESULT_ERROR_RADIO_OFF: 39 setStatus("Radio off"); 40 break; 41 } 42 unregisterReceiver(this); 43 } 44 }; 45 46 registerReceiver(br,new IntentFilter(SENT)); 47 48 //---when the SMS has been delivered--- 49 BroadcastReceiver br2 = new BroadcastReceiver(){ 50 @Override 51 public void onReceive(Context arg0, Intent arg1) { 52 switch (getResultCode()) 53 { 54 case Activity.RESULT_OK: 55 setStatus("对方已收到短信"); 56 break; 57 case Activity.RESULT_CANCELED: 58 setStatus("SMS not delivered"); 59 } 60 unregisterReceiver(this); 61 } 62 }; 63 registerReceiver(br2,new IntentFilter(DELIVERED)); 64 65 SmsManager sms = SmsManager.getDefault(); 66 sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI); 67 } 68 }