Android的短信接收类

Android的短信接收类
继承自BroadcastReceiver类,需要重写onReceive方法,当收到短信时就会自动触发onReceive方法,在onReceive方法中通过Toast来显示短信内容。

 public class SMSReceiver extends BroadcastReceiver
 {
     /*当收到短信时,就会触发此方法*/
     public void onReceive(Context context, Intent intent)
     {
         Bundle bundle = intent.getExtras();
         Object messages[] = (Object[]) bundle.get("pdus");
         SmsMessage smsMessage[] = new SmsMessage[messages.length];
         for (int n = 0; n < messages.length; n++)
         {
             smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
         }
         //产生一个Toast
         Toast toast = Toast.makeText(context, "短信内容: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
         //设置toast显示的位置
         toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 200);
         //显示该Toast
         toast.show();
     }
 }
 

 因为在项目中使用了短信接口,所以需要在AndroidManifest.xml中声明其权限,如橙色高亮显示:

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.yarin.android.Examples_04_05"
       android:versionCode="1"
       android:versionName="1.0">
     <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
     <application android:icon="@drawable/icon" android:label="@string/app_name">
         <activity android:name=".Activity01"
                   android:label="@string/app_name">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.LAUNCHER"/>
             </intent-filter>
         </activity>
     <receiver android:name=".SMSReceiver" android:enabled="true">  
         <intent-filter>  
             <action android:name="android.provider.Telephony.SMS_RECEIVED"/>  
         </intent-filter>  
     </receiver> 
     </application>
     <uses-sdk android:minSdkVersion="5" />
 </manifest>

相关推荐