Android中实现基本的短信拦截功能的代码示例

要点

1.在Manifest.xml里加"接收"SMS的权限



2.在Manifest.xml里注册一个receive


    
  
  
  
 

3.定义一个短信接收类,并且重写onReceive

//继承BroadcastReceiver
public class AutoSMS extends BroadcastReceiver 
{

 private String TAG="AutSMS";
 //广播消息类型
 public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
 //覆盖onReceive方法
 @Override
 public void onReceive(Context context, Intent intent) 
 {
.....

实例
下面是完整的代码:

Manifest.xml:

 
 
   
   
 
   
     
       
         
 
         
       
     
     
     
       
         
       
     
     
   
 
 

AutoSMS.java:

package com.xxh.autosms; 
 
import java.text.SimpleDateFormat; 
import java.util.Date; 
 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.telephony.SmsMessage; 
import android.util.Log; 
import android.widget.Toast; 
 
//继承BroadcastReceiver 
public class AutoSMS extends BroadcastReceiver  
{ 
 
  private String TAG="AutSMS"; 
  //广播消息类型 
  public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; 
  //覆盖onReceive方法 
  @Override 
  public void onReceive(Context context, Intent intent)  
  { 
    // TODO Auto-generated method stub 
    Log.i(TAG, "引发接收事件"); 
    //StringBuilder body=new StringBuilder("");//短信内容 
    //StringBuilder sender=new StringBuilder("");//发件人 
    //先判断广播消息 
    String action = intent.getAction(); 
    if (SMS_RECEIVED_ACTION.equals(action)) 
    { 
      //获取intent参数 
      Bundle bundle=intent.getExtras(); 
      //判断bundle内容 
      if (bundle!=null) 
      { 
        //取pdus内容,转换为Object[] 
        Object[] pdus=(Object[])bundle.get("pdus"); 
        //解析短信 
        SmsMessage[] messages = new SmsMessage[pdus.length]; 
        for(int i=0;i 
 

你可能感兴趣的:(Android中实现基本的短信拦截功能的代码示例)