Android发送接收短信的代码示例(本人验证OK)

本文介绍了一个简单的Android应用程序,用于发送和接收短信。该程序通过使用SmsManager API实现了短信发送功能,并通过BroadcastReceiver监听短信接收事件。代码示例涵盖了发送短信的Activity、短信接收器、UI布局文件及权限配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、SMS Activity 短信发送Class

  1. package cn.dccssq;  
  2.   
  3. import java.util.List;  
  4.   
  5. import android.app.Activity;  
  6. import android.app.PendingIntent;  
  7. import android.content.BroadcastReceiver;  
  8. import android.content.Context;  
  9. import android.content.Intent;  
  10. import android.content.IntentFilter;  
  11. import android.os.Bundle;  
  12. import android.telephony.SmsManager;  
  13. import android.view.View;  
  14. import android.widget.Button;  
  15. import android.widget.EditText;  
  16. import android.widget.Toast;  
  17.   
  18. public class SMS extends Activity {  
  19.       
  20.     String SENT_SMS_ACTION="SENT_SMS_ACTION";  
  21.     String DELIVERED_SMS_ACTION="DELIVERED_SMS_ACTION";  
  22.   
  23.     /** Called when the activity is first created. */  
  24.     @Override  
  25.     public void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         setContentView(R.layout.main);  
  28.           
  29.         Button btn = (Button)findViewById(R.id.btn);  
  30.         btn.setOnClickListener(new View.OnClickListener() {  
  31.               
  32.             public void onClick(View arg0) {  
  33.                 // TODO Auto-generated method stub  
  34.                 EditText telNoDELIVERED_SMS_ACTIONText =(EditText)findViewById(R.id.telNo);  
  35.                 EditText contentText = (EditText)findViewById(R.id.content);  
  36.                   
  37.                 String telNo = telNoText.getText().toString();  
  38.                 String content = contentText.getText().toString();  
  39.                 if (validate(telNo, content))  
  40.                 {  
  41.                     sendSMS(telNo, content);  
  42.                 }else{  
  43. //                  AlertDialog.Builder builder =  new AlertDialog.Builder(SMS.this);  
  44. //                  builder.setMessage("Please enter both phone number and message.")  
  45. //                  .setTitle("Error")  
  46. //                          .setCancelable(false)  
  47. //                          .setNegativeButton("OK",  
  48. //                                  new DialogInterface.OnClickListener() {  
  49. //                                      public void onClick(  
  50. //                                              DialogInterface dialog,  
  51. //                                              int id) {  
  52. //                                          dialog.cancel();  
  53. //                                      }  
  54. //                                  });  
  55. //                  AlertDialog alert = builder.create();  
  56. //                  alert.show();  
  57.                 }  
  58.             }  
  59.         });  
  60.     }  
  61.       
  62.     /** 
  63.      * Send SMS 
  64.      * @param phoneNumber 
  65.      * @param message 
  66.      */  
  67.     private void sendSMS(String phoneNumber, String message) {  
  68.           
  69.         //create the sentIntent parameter  
  70.         Intent sentIntent = new Intent(SENT_SMS_ACTION);  
  71.         PendingIntent sentPI = PendingIntent.getBroadcast(this0, sentIntent,  
  72.                 0);  
  73.         // create the deilverIntent parameter  
  74.         Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);  
  75.         PendingIntent deliverPI = PendingIntent.getBroadcast(this0,  
  76.                 deliverIntent, 0);  
  77.   
  78.         SmsManager sms = SmsManager.getDefault();  
  79.         if (message.length() > 70) {  
  80.             List<String> msgs = sms.divideMessage(message);  
  81.             for (String msg : msgs) {  
  82.                 sms.sendTextMessage(phoneNumber, null, msg, sentPI, deliverPI);  
  83.             }  
  84.         } else {  
  85.             sms.sendTextMessage(phoneNumber, null, message, sentPI, deliverPI);  
  86.         }  
  87.         Toast.makeText(SMS.this, R.string.message, Toast.LENGTH_LONG).show();  
  88.           
  89.         //register the Broadcast Receivers  
  90.         registerReceiver(new BroadcastReceiver(){  
  91.             @Override  
  92.             public void onReceive(Context _context,Intent _intent)  
  93.             {  
  94.                 switch(getResultCode()){  
  95.                     case Activity.RESULT_OK:  
  96.                         Toast.makeText(getBaseContext(),   
  97.                                 "SMS sent success actions",  
  98.                                 Toast.LENGTH_SHORT).show();  //短信发送成功
  99.                         break;  
  100.                     case SmsManager.RESULT_ERROR_GENERIC_FAILURE:  
  101.                         Toast.makeText(getBaseContext(),   
  102.                                 "SMS generic failure actions",  
  103.                                 Toast.LENGTH_SHORT).show();  
  104.                         break;  
  105.                     case SmsManager.RESULT_ERROR_RADIO_OFF:  
  106.                         Toast.makeText(getBaseContext(),  
  107.                                 "SMS radio off failure actions",  
  108.                                 Toast.LENGTH_SHORT).show();  
  109.                         break;  
  110.                     case SmsManager.RESULT_ERROR_NULL_PDU:  
  111.                         Toast.makeText(getBaseContext(),   
  112.                                 "SMS null PDU failure actions",  
  113.                                 Toast.LENGTH_SHORT).show();  
  114.                         break;  
  115.                 }  
  116.             }  
  117.         },  
  118.         new IntentFilter(SENT_SMS_ACTION));  
  119.         registerReceiver(new BroadcastReceiver(){  
  120.             @Override  
  121.             public void onReceive(Context _context,Intent _intent)  
  122.             {  
  123.                 Toast.makeText(getBaseContext(),   
  124.                         "SMS delivered actions",  
  125.                         Toast.LENGTH_SHORT).show();  //收信人已经成功接收            
  126.             }  
  127.         },  
  128.         new IntentFilter(DELIVERED_SMS_ACTION));  
  129.   
  130.     }  
  131.       
  132.     public boolean validate(String telNo, String content){  
  133.           
  134.         if((null==telNo)||("".equals(telNo.trim()))){  
  135.             Toast.makeText(this"please input the telephone No.!",Toast.LENGTH_LONG).show();  
  136.             return false;  
  137.         }  
  138.         if(!checkTelNo(telNo)){  
  139.             Toast.makeText(this"please input the right telephone No.!",Toast.LENGTH_LONG).show();  
  140.             return false;  
  141.         }  
  142.         if((null==content)||("".equals(content.trim()))){  
  143.             Toast.makeText(this"please input the message content!",Toast.LENGTH_LONG).show();  
  144.             return false;  
  145.         }  
  146.         return true;  
  147.     }  
  148.       
  149.     public boolean checkTelNo(String telNo){  
  150.         if("5556".equals(telNo)){  
  151.             return true;  
  152.         }else{  
  153.             String reg ="^0{0,1}(13[0-9]|15[0-9])[0-9]{8}$";   
  154.             return telNo.matches(reg);  
  155.         }  
  156.     }  
  157. }  

※1、为了测试模拟器间的通信,在checkTelNo方法中加入了以下代码的判断,实际开发中不需要。

     if("5556".equals(telNo)){
      return true;
     }

※2、Message信息均为Hard coding,为了便于多语言化和避免message的重复定义,在实际开发中应将message定义在strin.xml中。

2、ReceiverDemo 短信接收Class

  1. package cn.dccssq;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.telephony.SmsMessage;  
  8. import android.widget.Toast;  
  9.   
  10. public class ReceiverDemo extends BroadcastReceiver {  
  11.   
  12.     private static final String strRes = "android.provider.Telephony.SMS_RECEIVED";  
  13.       
  14.     @Override  
  15.     public void onReceive(Context arg0, Intent arg1) {  
  16.         // TODO Auto-generated method stub  
  17.         if(strRes.equals(arg1.getAction())){  
  18.             StringBuilder sb = new StringBuilder();  
  19.             Bundle bundle = arg1.getExtras();  
  20.             if(bundle!=null){  
  21.                 Object[] pdus = (Object[])bundle.get("pdus");  
  22.                 SmsMessage[] msg = new SmsMessage[pdus.length];  
  23.                 for(int i = 0 ;i<pdus.length;i++){  
  24.                     msg[i] = SmsMessage.createFromPdu((byte[])pdus[i]);  
  25.                 }  
  26.                   
  27.                 for(SmsMessage curMsg:msg){  
  28.                     sb.append("You got the message From:【");  
  29.                     sb.append(curMsg.getDisplayOriginatingAddress());  
  30.                     sb.append("】Content:");  
  31.                     sb.append(curMsg.getDisplayMessageBody());  
  32.                 }  
  33.                 Toast.makeText(arg0,   
  34.                         "Got The Message:" + sb.toString(),  
  35.                         Toast.LENGTH_SHORT).show();       
  36.             }  
  37.         }  
  38.     }  
  39.   
  40. }  

3、main.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7. <TextView    
  8.     android:layout_width="fill_parent"   
  9.     android:layout_height="wrap_content"   
  10.     android:text="@string/mobile"  
  11.     />  
  12. <EditText    
  13.     android:id="@+id/telNo"  
  14.     android:layout_width="fill_parent"   
  15.     android:layout_height="wrap_content"   
  16.     android:numeric="integer"  
  17.     />    
  18. <TextView    
  19.     android:layout_width="fill_parent"   
  20.     android:layout_height="wrap_content"   
  21.     android:text="@string/content"  
  22.     />   
  23. <EditText    
  24.     android:id="@+id/content"  
  25.     android:layout_width="fill_parent"   
  26.     android:layout_height="wrap_content"   
  27.     android:minLines="3"  
  28.     />   
  29. <Button    
  30.     android:id="@+id/btn"  
  31.     android:layout_width="fill_parent"   
  32.     android:layout_height="wrap_content"   
  33.     android:text="@string/button"  
  34.     />  
  35. </LinearLayout>  

4、strings.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, SMS!</string>  
  4.     <string name="app_name">SMS</string>  
  5.     <string name="mobile">Please input the TEL No.</string>  
  6.     <string name="content">Please input the SMS content.</string>  
  7.     <string name="button">SEND</string>  
  8.     <string name="message">send successfully!</string>  
  9. </resources>  

5、AndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="cn.dccssq"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".SMS"  
  8.                   android:label="@string/app_name">  
  9.             <intent-filter>  
  10.                 <action android:name="android.intent.action.MAIN" />  
  11.                 <category android:name="android.intent.category.LAUNCHER" />  
  12.             </intent-filter>  
  13.         </activity>  
  14.     <receiver android:name=".ReceiverDemo" android:enabled="true" >  
  15.         <intent-filter>  
  16.             <action android:name="android.provider.Telephony.SMS_RECEIVED" />  
  17.         </intent-filter>  
  18.     </receiver>  
  19.     </application>  
  20.     <uses-sdk android:minSdkVersion="7" />  
  21.     <uses-permission android:name="android.permission.SEND_SMS"/>  
  22.     <uses-permission android:name="android.permission.RECEIVE_SMS"/>  
  23. </manifest>  
这是一个自己开发的Android 直接发送短信方法附上代码Android短信功能,包括了对内容合法性的验证发送完成弹出提示。自己开发的直接发送短信的方法:   private void sendSMS(String telNo,String smsStr,View v){    PendingIntent pi=    PendingIntent.getActivity(this, 0, new Intent(this,Sample_11_1.class), 0);    SmsManager sms=SmsManager.getDefault();    sms.sendTextMessage(telNo, null, smsStr, pi, null);    //短信发送成功给予提示    Toast.makeText(    Sample_11_1.this, //上下文    "恭喜你,短信发送成功!", //提示内容    5000 //信息显示时间    ).show();    v.setEnabled(true);//短信发送完成后恢复发送按钮的可用状态   }   对手机号码和短信内容的验证部分:   //获取输入的电话号码   EditText etTel=(EditText)findViewById(R.id.EditText02);   String telStr=etTel.getText().toString();   //获取输入的短信内容   EditText etSms=(EditText)findViewById(R.id.EditText01);   String smsStr=etSms.getText().toString();   //判断号码字符串是否合法   if(PhoneNumberUtils.isGlobalPhoneNumber(telStr)){//合法则发送短信    v.setEnabled(false);//短信发送完成前将发送按钮设置为不可用    sendSMS(telStr,smsStr,v);   }   else{//不合法则提示    Toast.makeText(    Sample_11_1.this, //上下文    "电话号码不符合格式!!!", //提示内容    5000//信息显示时间    ).show();   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值