Android中监听短信的两种方法


1、监听广播

缺点,因为优先级的原因可能接收不到。

代码:

public static final String TAG = "ImiChatSMSReceiver";

  public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

  public void onReceive(Context context, Intent intent)
  {
    if (intent.getAction().equals(SMS_RECEIVED_ACTION))
    {
      SmsMessage[] messages = getMessagesFromIntent(intent);

      for (SmsMessage message : messages)
      {

        String text = message.getOriginatingAddress() + " : " +

        message.getDisplayOriginatingAddress() + " : " +

        message.getDisplayMessageBody() + " : " +

        message.getTimestampMillis();

        String num = message.getOriginatingAddress();
        Log.i(TAG, "-------------" + text);
        Toast.makeText(context, text, Toast.LENGTH_LONG).show();
        sendMessage(num, "来自" + num + "的短信已经收到", context);

        context.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, new SmsObserver(new Handler(), context));
      }
    }
  }

  public void sendMessage(String num, String text, Context context)
  {
    SmsManager smsManager = SmsManager.getDefault();
    PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, new Intent(), 0);
    String strContent = text;

    smsManager.sendTextMessage(num, null, strContent, sentIntent, null);

    TelephonyManager tl = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    int itype = tl.getPhoneType();
    Log.i(TAG, "-------------" + "当前卡类型为:" + itype);
    if (itype == TelephonyManager.PHONE_TYPE_GSM)
    {
      Toast.makeText(context, "当前卡类型为:GSM", Toast.LENGTH_LONG).show();
    }
    else if (itype == TelephonyManager.PHONE_TYPE_CDMA)
    {
      Toast.makeText(context, "当前卡类型为 : CDMA", Toast.LENGTH_LONG).show();
    }
    else if (itype == TelephonyManager.PHONE_TYPE_NONE)
    {
      Toast.makeText(context, "当前卡类型为:NONE", Toast.LENGTH_LONG).show();
    }
  }

  public final SmsMessage[] getMessagesFromIntent(Intent intent)
  {

    Object[] messages = (Object[]) intent.getSerializableExtra("pdus");

    byte[][] pduObjs = new byte[messages.length][];

    for (int i = 0; i < messages.length; i++)

    {

      pduObjs[i] = (byte[]) messages[i];

    }

    byte[][] pdus = new byte[pduObjs.length][];

    int pduCount = pdus.length;

    SmsMessage[] msgs = new SmsMessage[pduCount];

    for (int i = 0; i < pduCount; i++)

    {

      pdus[i] = pduObjs[i];

      msgs[i] = SmsMessage.createFromPdu(pdus[i]);

    }

    return msgs;

  }



2、采用观察方法,监听短信数据库

public class SmsObserver extends ContentObserver
{

  private Context mContext;

  public SmsObserver(Handler handler , Context context)
  {
    super(handler);
    mContext = context;
  }
  
  public void onChange(boolean selfChange) 
  { 
    super.onChange(selfChange); 
    Cursor cursor =null; 
    try
    {
      //读取收件箱中的短信 
      cursor = mContext.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, "date desc"); 
      String body;
      boolean hasDone =false;
      if (cursor !=null)
      { 
        while (cursor.moveToNext())
        {
          body = cursor.getString(cursor.getColumnIndex("body"));
          if(body !=null)//&& body.equals("【startMyActivity】"
          {
            hasDone =true;
            break;
          }
          if (hasDone)
          {
            break;
          }
        } 
      } 
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      if(cursor!=null)    cursor.close();
    }
  }

}


用到的权限:

<uses-permission android:name="android.permission.SEND_SMS" />
  <uses-permission android:name="android.permission.RECEIVE_SMS" />
  <uses-permission android:name="android.permission.READ_SMS" />



相关阅读:
Android HTTP网络请求的异步实现
C#中事件的动态调用实现方法
两个php日期控制类实例
win2008 R2 WEB环境配置之MYSQL 5.6.22安装版安装配置方法
win8.1系统开机屏幕总是会闪一下或黑屏一会才进入桌面的故障原因及解决方法
BootStrap使用popover插件实现鼠标经过显示并保持显示框
PHP如何利用P3P实现跨域
JavaScript获取页面上被选中文字的方法技巧
javascript+canvas制作九宫格小程序
asp.net错误页面处理示例分享
举例剖析C++中引用的本质及引用作函数参数的使用
win7旗舰版系统更新补丁使用bitlocker时输入密码出现 “无效的语法”的解决方法
php根据年月获取季度的方法
Javascript获取统一管理的提示语(message)
快速导航

Copyright © 2016 phpStudy |