Android监听短信到来并自动填充到输入框中
基本原理:通过ContentObserver观察者监听sms数据库的改变,当有变化时检测是否是来自指定号码的短信,如果是的话就通过正则表达式获得需要的内容,然后贴代码 (*^__^*) 嘻嘻……:
1 /** 2 * 3 * @ClassName: SmsContent 4 * @Description: 短信监听类 5 * @author guoyizhe 6 * @email [email protected] 7 * @date 2015-6-9 下午3:30:12 8 * 9 */ 10 public class SmsContent extends ContentObserver { 11 12 public static final String SMS_URI_INBOX = "content://sms/inbox"; 13 private Activity activity = null; 14 private String smsContent = ""; 15 private EditText verifyText = null; 16 private Handler handler; 17 private int SMS_CONTENT = 1; 18 19 public SmsContent(Activity activity, Handler handler, EditText verifyText) { 20 super(handler); 21 this.activity = activity; 22 this.verifyText = verifyText; 23 this.handler = handler; 24 } 25 26 @Override 27 public void onChange(boolean selfChange) { 28 super.onChange(selfChange); 29 Cursor cursor = null; 30 // 读取收件箱中指定号码的未读短信,一般只监听自己公司使用的短信通道号码,如果有多个,查询语句改为 address in (xxx,xxx)就可以了 31 cursor = activity.getContentResolver().query(Uri.parse(SMS_URI_INBOX), new String[] { "_id", "address", "body", "read" }, "address =? and read=?", 32 new String[] { "5554" ,"0" }, "date desc"); 33 if (cursor != null) {//有未读短信 34 cursor.moveToFirst(); 35 if (cursor.moveToFirst()) {//这里也是针对一条,多条的话使用while循环遍历出即可 36 String smsbody = cursor.getString(cursor.getColumnIndex("body")); 37 String regEx = "[^0-9]"; 38 Pattern p = Pattern.compile(regEx); 39 Matcher m = p.matcher(smsbody.toString()); 40 smsContent = m.replaceAll("").trim().toString(); 41 verifyText.setText(smsContent); 42 } 43 //通过handler可以处理许多其他的事务,这里只是举个栗子 44 handler.obtainMessage(SMS_CONTENT, verifyText.getText().toString()).sendToTarget(); 45 cursor.close(); 46 } 47 } 48 }
然后是主Activity:
1 /** 2 * 3 * @ClassName: MainActivity 4 * @Description: 监听到来的短信并自动填充,也可以处理一些事件 5 * @author guoyizhe 6 * @email [email protected] 7 * @date 2015-6-9 下午2:17:56 8 * 9 */ 10 public class MainActivity extends Activity { 11 private Handler handler = new Handler(){ 12 public void handleMessage(android.os.Message msg) { 13 switch(msg.what){ 14 case 1://处理短信到来后事件 15 //TODO 16 break; 17 } 18 }; 19 }; 20 21 @Override 22 protected void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 setContentView(R.layout.activity_main); 25 EditText text = (EditText) findViewById(R.id.smsObserver); 26 SmsContent content = new SmsContent(MainActivity.this, handler, text); 27 // 注册短信变化监听 28 this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, content); 29 } 30 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。