转载请标明出处:http://blog.csdn.net/qq1221jyj/article/details/47000977
最近做项目。老板提到自动填写后台发送的短信验证码狠人性化,老板的话。就是我们的目标,那就开始做咯。
其实也很简单。不多说直接上代码
public class SmsContent extends ContentObserver{
/**
* Creates a content observer.
*
* @param handler The handler to run {@link #onChange} on, or null if none.
*/
public static final String SMS_URI_INBOX = "content://sms/inbox";
private Activity activity = null;
private String smsContent = "";
private EditText verifyText = null;
private String ergouhaitao="***";
public SmsContent(Activity activity,Handler handler,EditText verifyText) {
super(handler);
this.activity = activity;
this.verifyText = verifyText;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Cursor cursor = null;
// 读取收件箱中指定号码的短信
cursor = activity.managedQuery(Uri.parse(SMS_URI_INBOX), new String[] { "_id", "address", "read" ,"body" },null,null,null);**managedQuery()查看该方法的源码 ,可以了解到更多的功能需求,本人菜鸟,大家自己看源码吧~**
if (cursor != null) {// 如果短信为未读模式
cursor.moveToFirst();
if (cursor.moveToFirst()) {
**String smsbody = cursor.getString(cursor.getColumnIndex("body"));***这smsbody是收到的短信内容,我是根据短信内容做得处理。*
String judge= smsbody.replace(" ", "");
Log.e("judge",judge);
Log.e("Jyj",judge.contains(ergouhaitao)+"");
if (judge.contains(ergouhaitao)){
String regEx = "[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(smsbody.toString());
smsContent = m.replaceAll("").trim().toString();
verifyText.setText(smsContent);
}
}
}
if(Build.VERSION.SDK_INT < 14) {
cursor.close();
}
}
}
调用时:SmsContent content = new SmsContent(MainActivity.this, new Handler(), main_ed);
this.getContentResolver().registerContentObserver(Uri.parse(“content://sms/”), true, content);
最后别忘了添加权限:
上面的代码就可以直接拿来用了。
小菜比一个,不喜勿喷。大家共同进步。
参考:http://blog.sina.com.cn/s/blog_87dc03ea0101dvus.html