一般在账号注册时我们会用到自动读取短信里的随机验证码,增强用户体验
① 短信一共有以下的权限
<uses-permission android:name="android.permission.SEND_SMS" />
<!-- 阅读消息 -->
<uses-permission android:name="android.permission.READ_SMS" />
<!-- 写入消息 -->
<uses-permission android:name="android.permission.WRITE_SMS" />
<!-- 接收消息 -->
<uses-permission android:name="android.permission.RECEIVE_SMS" />
②在activity中注册内容观察者监听短信的变化
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//随机验证码会填到EditText中
EditText edit=(EditText) findViewById(R.id.edit);
SmsContent content = new SmsContent(MainActivity.this, new Handler(), edit);
// 注册短信变化监听,写为content://sms/inbox 传说会监听不到
this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"),true , content);
}
}
③创建一个类继承ContentObserver 重写onChange 方法
public class SmsContent extends ContentObserver {
public static final String SMS_URI_INBOX = "content://sms/inbox";
private Activity activity = null;
private String smsContent = "";
//传递过来的EditText
private EditText verifyText = null;
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.getContentResolver().query(Uri.parse(SMS_URI_INBOX),
// type=1 接受 type=2发送 read=0未读 1 以读
null, "address=? and type=? and read=? ",new String[]{"15555215554","1","0"}, "date desc");
if (cursor != null) {
cursor.moveToFirst();
if (cursor.moveToNext()) {
String smsbody = cursor
.getString(cursor.getColumnIndex("body"));
Log.e("smsbody=======================" , smsbody);
//匹配0-9的数字
String regEx = "[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(smsbody.toString());
smsContent = m.replaceAll("").trim().toString();
verifyText.setText(smsContent);
}
}
//使用完成了,要关闭,防止内存泄露
cursor.close();
}
}
④说明:
一 .activity.getContentResolver().query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder)
参数:1 uri
2 要查询的字段,null 表示全部都查询,new String[] {"_id", "address", "body", "read" } 表示要查询这几个字段
3 要查询的条件 如: "address=15555215554" (那呢条件4就为null)也可以和条件4配合使用
4 条件3对应的值. 如条件3为 "address=? and type=? and read=? " 那么条件4 new String[]{"15555215554","1","0"} 数组的的每一个值和条件3对应
二 短信的Uri共有一下几种:
content://sms/inbox 收件箱
content://sms/sent 已发送
content://sms/draft 草稿
content://sms/outbox 发件箱 (正在发送的信息)
content://sms/failed 发送失败
content://sms/queued 待发送列表 (比如开启飞行模式后,该短信就在待发送列表里)