Android中监听短信的两种方法
1、监听广播
缺点,因为优先级的原因可能接收不到。
代码:
publicstaticfinalStringTAG="ImiChatSMSReceiver"; publicstaticfinalStringSMS_RECEIVED_ACTION="android.provider.Telephony.SMS_RECEIVED"; publicvoidonReceive(Contextcontext,Intentintent) { if(intent.getAction().equals(SMS_RECEIVED_ACTION)) { SmsMessage[]messages=getMessagesFromIntent(intent); for(SmsMessagemessage:messages) { Stringtext=message.getOriginatingAddress()+":"+ message.getDisplayOriginatingAddress()+":"+ message.getDisplayMessageBody()+":"+ message.getTimestampMillis(); Stringnum=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,newSmsObserver(newHandler(),context)); } } } publicvoidsendMessage(Stringnum,Stringtext,Contextcontext) { SmsManagersmsManager=SmsManager.getDefault(); PendingIntentsentIntent=PendingIntent.getBroadcast(context,0,newIntent(),0); StringstrContent=text; smsManager.sendTextMessage(num,null,strContent,sentIntent,null); TelephonyManagertl=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); intitype=tl.getPhoneType(); Log.i(TAG,"-------------"+"当前卡类型为:"+itype); if(itype==TelephonyManager.PHONE_TYPE_GSM) { Toast.makeText(context,"当前卡类型为:GSM",Toast.LENGTH_LONG).show(); } elseif(itype==TelephonyManager.PHONE_TYPE_CDMA) { Toast.makeText(context,"当前卡类型为:CDMA",Toast.LENGTH_LONG).show(); } elseif(itype==TelephonyManager.PHONE_TYPE_NONE) { Toast.makeText(context,"当前卡类型为:NONE",Toast.LENGTH_LONG).show(); } } publicfinalSmsMessage[]getMessagesFromIntent(Intentintent) { Object[]messages=(Object[])intent.getSerializableExtra("pdus"); byte[][]pduObjs=newbyte[messages.length][]; for(inti=0;i<messages.length;i++) { pduObjs[i]=(byte[])messages[i]; } byte[][]pdus=newbyte[pduObjs.length][]; intpduCount=pdus.length; SmsMessage[]msgs=newSmsMessage[pduCount]; for(inti=0;i<pduCount;i++) { pdus[i]=pduObjs[i]; msgs[i]=SmsMessage.createFromPdu(pdus[i]); } returnmsgs; }
2、采用观察方法,监听短信数据库
publicclassSmsObserverextendsContentObserver { privateContextmContext; publicSmsObserver(Handlerhandler,Contextcontext) { super(handler); mContext=context; } publicvoidonChange(booleanselfChange) { super.onChange(selfChange); Cursorcursor=null; try { //读取收件箱中的短信 cursor=mContext.getContentResolver().query(Uri.parse("content://sms/inbox"),null,null,null,"datedesc"); Stringbody; booleanhasDone=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(Exceptione) { e.printStackTrace(); } finally { if(cursor!=null)cursor.close(); } } }
用到的权限:
<uses-permissionandroid:name="android.permission.SEND_SMS"/> <uses-permissionandroid:name="android.permission.RECEIVE_SMS"/> <uses-permissionandroid:name="android.permission.READ_SMS"/>