自己总结的获取验证码之后写入textview

思路是在这个界面上注册监听短信的广播,

private IntentFilter intentFilter = new IntentFilter(
        "android.provider.Telephony.SMS_RECEIVED");
定义方法内容
private smsBroadcastReceiver smsBR = new smsBroadcastReceiver();

intentFilter.setPriority(2147483647);// 设置优先级
在开始的方法中注册

@Override
protected void onStart() {
    super.onStart();
    registerReceiver(smsBR, intentFilter);

关闭的时候关闭广播

@Override
protected void onStop() {
    super.onStop();
    unregisterReceiver(smsBR);
}
 /**
     * 内部类 用于监听短信
     * 具体请自己改写某方法 by lcf_炒饭
     */
    private class smsBroadcastReceiver extends BroadcastReceiver {
        @TargetApi(Build.VERSION_CODES.DONUT)
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            Object messages[] = (Object[]) bundle.get("pdus");

            boolean isnumber;
            SmsMessage smsMessage[] = new SmsMessage[messages.length];
            for (int n = 0; n < messages.length; n++) {
                smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
//                ("号码:"+smsMessage[n].getOriginatingAddress()+
//                        "內容:"+smsMessage[n].getMessageBody());
                Log.v("number", smsMessage[n].getOriginatingAddress());
                Log.v("msg", smsMessage[n].getMessageBody());
                if (smsMessage[n].getMessageBody().contains("验证码")) {
                    for (int i = 0; i < smsMessage[n].getMessageBody().length(); i++) {
                        smsMessage[n].getMessageBody().substring(i, i + 1);
                        isnumber = isNumeric(smsMessage[n].getMessageBody().substring(i, i + 1));
                        if (isnumber) {
                            String code = smsMessage[n].getMessageBody().substring(i, i + 6);
                            editCode.setText(code);
                            return;
                        }
                    }
                }
            }
        }
    }

最后别忘记在配置文件中加上权限 

   
   
   
   


你可能感兴趣的:(自己总结的获取验证码之后写入textview)