短信 short message service,简称SMS 是用户通过手机或其他电信终端直接发送或接收的文字或数字信息,用户每次能接收和发送短信的字符数,是160个英文或数字字符,或者70个中文字符。现在我通过Emulator Control向5554发送短信,如果5554收到短信将会提示,下面我们先看一下发来的短信提示图:

我们看一下方法类:

 
  
  1. package com.smart.sms; 
  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 SmsReceiver extends BroadcastReceiver{ 
  11.  
  12.     @Override 
  13.     public void onReceive(Context context, Intent intent) { 
  14.          
  15.         if("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())){ 
  16.          
  17.             StringBuilder sb=new StringBuilder(); 
  18.             // 接收由SMS传过来的数据 
  19.             Bundle bundle=intent.getExtras(); 
  20.             // 判断是否有数据 
  21.             if(bundle!=null){ 
  22.                 //通过pdus可以获得接收到的所有短信消息 
  23.                 Object[] objArray=(Object[]) bundle.get("pdus"); 
  24.                 //构建短信对象array,并依据收到的对象长度来创建array的大小  
  25.                 SmsMessage[] message=new SmsMessage[objArray.length]; 
  26.                  
  27.                 for (int i = 0; i < objArray.length; i++) { 
  28.                     message[i]=SmsMessage.createFromPdu((byte[])objArray[i]); 
  29.                 } 
  30.                 // 将送来的短信合并自定义信息于StringBuilder当中  
  31.                 for (SmsMessage currentMessage:message) { 
  32.                     sb.append("短信来源"); 
  33.                     // 获得接收短信的电话号码 
  34.                     sb.append(currentMessage.getDisplayMessageBody()); 
  35.                     sb.append("\n------短信内容------\n"); 
  36.                     // 获得短信的内容 
  37.                     sb.append(currentMessage.getDisplayMessageBody()); 
  38.                      
  39.                 } 
  40.                 Intent mainIntent=new Intent(context,SmsActivity.class); 
  41.                 mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
  42.                 context.startActivity(mainIntent); 
  43.                 Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show(); 
  44.                  
  45.             } 
  46.              
  47.              
  48.         } 
  49.     } 
  50.  

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:id="@+id/textview" 
  9.     android:layout_width="fill_parent"  
  10.     android:layout_height="wrap_content"  
  11.     android:textSize="15dp" 
  12.     android:text="SMART收短信提示" 
  13.     /> 
  14. </LinearLayout>