android 通过广播获取指定联系人短信内容
在配置文件中添加以下权限
<uses-permission android:name="android.permission.RECEIVE_SMS" />
new一个新的广播SMSBroadcast
package aviationboss.broadcast; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Message; import android.telephony.SmsMessage; import android.util.Log; import aviationboss.activity.PaymentActivity; /* * 判断是否接收到验证信息,并获取验证码 */ public class SMSBroadcast extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent arg1) { // TODO Auto-generated method stub Log.i("lwx", "receive sms"); Bundle bundler = arg1.getExtras();//获取所拦截的短信 if(bundler!=null){ StringBuilder body = new StringBuilder(); StringBuilder number = new StringBuilder(); Object[] _pdus = (Object[]) bundler.get("pdus"); SmsMessage[] message = new SmsMessage[_pdus.length]; for(int i = 0;i<_pdus.length;i++){ message[i] = SmsMessage.createFromPdu((byte[])_pdus[i]); } for(SmsMessage sm:message){ body.append(sm.getDisplayMessageBody()); number.append(sm.getDisplayOriginatingAddress()); } String bodyStr = body.toString(); String numberStr = number.toString(); Log.i("lwx", "sms body = "+bodyStr); Log.i("lwx", "sms number = "+numberStr); if(numberStr.contains("106550101872158437")){//这里判断拦截短信的号码 try{ int index_1 = bodyStr.indexOf(":"); int index_2 = bodyStr.indexOf(";"); String str = bodyStr.substring(index_1+1, index_2).trim(); Log.i("lwx", "str="+str); int count = Integer.parseInt(str); if(count>0){ if(PaymentActivity.handler!=null){ Message msg = new Message(); msg.what = 25; msg.obj = count; PaymentActivity.handler.sendMessage(msg);//将需要的内容发送给activity更新界面 } } }catch(Exception e){ e.printStackTrace(); } } } } }
配置文件中添加改广播,并设置广播拦截的动作
<receiver android:name="aviationboss.broadcast.SMSBroadcast" > <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>