public class GetSmsContent extends ContentObserver{ public final String SMS_URI_INBOX = "content://sms/inbox"; private Activity activity = null; private String smsContent = ""; private EditText verifyText = null; private String SMS_BODY = "【我在濟南】%";//短息內容包含【我在濟南】 public GetSmsContent(Activity activity, Handler handler, EditText verifyText) { super(handler); this.activity = activity; this.verifyText = verifyText; } /** * This method is called when a content change occurs. * 當短信箱(收到/刪除/發送 一條短信)發生變換時,該方法才能被調用。 */ @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Cursor cursor = null;// 光標 // 讀取收件箱中短信內容中包含【我在濟南】的短信 cursor = activity.managedQuery(Uri.parse(SMS_URI_INBOX), new String[] { "_id", "address", "body", "read" }, //要讀取的屬性 "body like ?", //查詢條件是什麼 new String[] { SMS_BODY },//查詢條件賦值 "date desc");//排序 if (cursor != null) {// 若是短信爲未讀模式 cursor.moveToFirst(); if (cursor.moveToFirst()) { String smsbody = cursor.getString(cursor.getColumnIndex("body")); System.out.println("smsbody=======================" + smsbody); //截取短信內容中第一個逗號以前的字符串。而後經過正則表達式找出字符串中的數字。 String s = smsbody.substring(0, smsbody.indexOf(",")); String regEx = "[^0-9]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(s.toString()); smsContent = m.replaceAll("").trim().toString(); if(verifyText != null && null!=smsContent && !"".equals(smsContent)){ verifyText.setText(smsContent); verifyText.setSelection(smsContent.length()); } } } } }
調用方法:在Activity的oncreate方法裏面註冊:java
GetSmsContent content = new GetSmsContent(RegisterByPhone.this, new Handler(), edit_yzm);
// 註冊短信變化監聽
this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, content);正則表達式