首先添加权限
android
:name=
"android.permission.SEND_SMS"
/>
android
:name=
"android.permission.READ_SMS"
/>
android
:name=
"android.permission.WRITE_SMS"
/>
android
:name=
"android.permission.RECEIVE_SMS"
/>
这段代码是获取手机短信内的第一条信息
private Uri SMS_INBOX = Uri.parse("content://sms/");
public void getSmsFromPhone() {
ContentResolver cr = getContentResolver();
String[] projection = new String[] { "body" };//"_id", "address", "person",, "date", "type
String where = " address = '10010' " ;
Cursor cur = cr.query(SMS_INBOX, projection, null, null, "date desc");
if (null == cur)
return;
if(cur.moveToNext()) {
// int number = cur.getInt(cur.getColumnIndex("address"));//手机号
// String name = cur.getString(cur.getColumnIndex("person"));//联系人姓名列表
String body = cur.getString(cur.getColumnIndex("body"));
System.out.println(" **************"+body);
//这里我是要获取自己短信服务号码中的验证码~~
Pattern pattern = Pattern.compile(" [a-zA-Z0-9]{10}");
Matcher matcher = pattern.matcher(body);
if (matcher.find()) {
String res = matcher.group().substring(1, 11);
System.out.println("======》"+res);
}
}
}
监听手机新来短信
首先注册一个广播
public class
SmsReciver
extends
BroadcastReceiver
在AndroidManifest.xml注册
android
:name=
".SmsReciver"
>
android
:priority=
"999"
>
android
:name=
"android.provider.Telephony.SMS_RECEIVED"
/>
广播类里
public class SmsReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("监听到来短信");
Bundle bundle = intent.getExtras();
SmsMessage msg = null;
if (null != bundle) {
Object[] smsObj = (Object[]) bundle.get("pdus");
for (Object object : smsObj) {
msg = SmsMessage.createFromPdu((byte[]) object);
Date date = new Date(msg.getTimestampMillis());//时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String receiveTime = format.format(date);
System.out.println("number:" + msg.getOriginatingAddress()
+ " body:" + msg.getDisplayMessageBody() + " time:"
+ msg.getTimestampMillis());
//在这里写自己的逻辑
if (msg.getOriginatingAddress().equals("10086")) {
//TODO
}
}
}
}
}