```
public class PhoneCode extends ContentObserver {
private Context mContext;
private String code;
private SmsListener mListener;
private Cursor mCursor;
private int index = 0;
public PhoneCode(Context context, Handler handler, SmsListener listener) {
super(handler);
this.mContext = context;
this.mListener = listener;
}
@
Override public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.d("验证码", "onChange");
index++;
mCursor = mContext.getContentResolver().query(Uri.parse("content://sms/"), new String[]{"_id", "address", "read", "body", "date"}, null,
null, "date desc");
if (mCursor == null) {
return;
}
while (mCursor.moveToNext()) {
String address = mCursor.getString(mCursor.getColumnIndex("address"));
String body = mCursor.getString(mCursor.getColumnIndex("body"));
if (!address.endsWith("268082")) {
return;
}
String regEx = "(?<![0-9])([0-9]{" + 4 + "})(?![0-9])";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(body);
if (matcher.find()) {
code = matcher.group();
if (mListener != null) {
mListener.onResult(code, index);
}
}
}
if (mCursor != null) {
mCursor.close();
}
}
public interface SmsListener {
void onResult(String result, int index);
}
}
```