Android 短信验证码自动填写
程序员文章站
2024-02-05 23:00:10
android 短信验证码自动填写
1.自定义observer监听短信数据库变化(注意添加短信权限)
import android.app.activity;...
android 短信验证码自动填写
1.自定义observer监听短信数据库变化(注意添加短信权限)
import android.app.activity; import android.content.contentresolver; import android.database.contentobserver; import android.database.cursor; import android.net.uri; import android.os.handler; import android.text.textutils; import java.util.regex.matcher; import java.util.regex.pattern; /** * created by 001 on 17/3/22. */ public class smsobserver extends contentobserver { public static final string sms_uri_inbox = "content://sms/inbox"; private activity activity = null; private string smscontent = ""; private smslistener listener; public smsobserver(activity activity, handler handler, smslistener listener) { super(handler); this.activity = activity; this.listener = listener; } @override public void onchange(boolean selfchange) { super.onchange(selfchange); cursor cursor = null; // 读取收件箱中含有某关键词的短信 contentresolver contentresolver = activity.getcontentresolver(); cursor = contentresolver.query(uri.parse(sms_uri_inbox), new string[] { "_id", "address", "body", "read" }, "body like ? and read=?", new string[] { "%关键词%", "0" }, "date desc"); if (cursor != null) { cursor.movetofirst(); if (cursor.movetofirst()) { string smsbody = cursor .getstring(cursor.getcolumnindex("body")); string regex = "[^0-9]"; pattern p = pattern.compile(regex); matcher m = p.matcher(smsbody.tostring()); smscontent = m.replaceall("").trim().tostring(); if (!textutils.isempty(smscontent)) { listener.onresult(smscontent); } } } } /* * 短信回调接口 */ public interface smslistener { /** * 接受sms状态 * * @title: onresult */ void onresult(string smscontent); } }
2.使用:
smsobserver smsobserver = new smsobserver(this, new handler(), new smsobserver.smslistener() { @override public void onresult(string smscontent) { //根据需求写 //如:edittext.settext(smscontent); } });this.getcontentresolver().registercontentobserver(uri.parse("content://sms/"), true, smsobserver);
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!