怎么在Android中获取短信验证码
本篇文章为大家展示了怎么在Android中获取短信验证码,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
为玉溪等地区用户提供了全套网页设计制作服务,及玉溪网站建设行业解决方案。主营业务为成都网站设计、成都网站制作、玉溪网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
MainActivity
public class MainActivity extends AppCompatActivity { public static TextView mText; private SmsContent content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (this.checkSelfPermission(Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) { //申请READ_SMS权限 ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_SMS}, 1); } mText = (TextView) findViewById(R.id.text); content = new SmsContent(new Handler(),this); //注册短信变化监听 this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, content); } @Override protected void onDestroy() { super.onDestroy(); this.getContentResolver().unregisterContentObserver(content); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); doNext(requestCode,grantResults); } private void doNext(int requestCode, int[] grantResults) { if (requestCode == 1) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else { // Permission Denied } } } }
SmsContent
class SmsContent extends ContentObserver { private Cursor cursor = null; private Context context; public SmsContent(Handler handler,Context context) { super(handler); this.context = context; } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Log.i("SMSTest","Begin"); //读取收件箱中指定号码的短信 // cursor = context.getContentResolver().query(Uri.parse("content://sms/inbox"), new String[]{"_id", "address", "read", "body"}, // " address=? and read=?", new String[]{"10086", "0"}, "_id desc");//按id排序,如果按date排序的话,修改手机时间后,读取的短信就不准了 cursor = context.getContentResolver().query(Uri.parse("content://sms/inbox"), new String[]{"_id", "address", "read", "body"}, null, null, "_id desc"); Log.i("SMSTest","cursor.isBeforeFirst(): " + cursor.isBeforeFirst() + " cursor.getCount(): " + cursor.getCount()); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); int smsbodyColumn = cursor.getColumnIndex("body"); String smsBody = cursor.getString(smsbodyColumn); Log.i("SMSTest","smsBody = " + smsBody); MainActivity.mText.setText(getDynamicPassword(smsBody)); } //在用managedQuery的时候,不能主动调用close()方法, 否则在Android 4.0+的系统上, 会发生崩溃 if(Build.VERSION.SDK_INT < 14) { cursor.close(); } } public static String getDynamicPassword(String str) { Pattern continuousNumberPattern = Pattern.compile("[0-9\\.]+"); Matcher m = continuousNumberPattern.matcher(str); String dynamicPassword = ""; while(m.find()){ if(m.group().length() == 6) { System.out.print(m.group()); dynamicPassword = m.group(); } } return dynamicPassword; } }
上述方法未读短信多了之后会同时上传2条验证码信息,可以根据cursor.getCount()来控制下。。。
下面第二种方法在oppo r9s上不见效果。。各位使用的小伙伴注意哦
public class SmsReceiver extends BroadcastReceiver { public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; private boolean flag = false; private String msgBody; private String msgAddress; public SmsReceiver() { Log.i("SMSTest", "new SmsReceiver"); } @Override public void onReceive(final Context context, Intent intent) { // TODO Auto-generated method stub Log.i("SMSTest", "jie shou dao"); Cursor cursor = null; try { if (SMS_RECEIVED.equals(intent.getAction())) { Log.d("SMSTest", "sms received!"); Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); final SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < pdus.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } if (messages.length > 0) { msgBody = messages[0].getMessageBody(); msgAddress = messages[0].getOriginatingAddress(); long msgDate = messages[0].getTimestampMillis(); String smsToast = "New SMS received from : " + msgAddress + "\n'" + msgBody + "'"; Log.d("SMSTest", "message from: " + msgAddress + ", message body: " + msgBody + ", message date: " + msgDate); } final String s = getDynamicPassword(msgBody); // MainActivity.mText.setText(s); if (s.length() != 0) { new AsyncTask() { @Override protected Void doInBackground(String... strings) { try { URL url = new URL(strings[0]); HttpURLConnection connect = (HttpURLConnection) url.openConnection(); InputStream is = connect.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { Log.i("SMSTest", "line = " + line); JSONObject obj = new JSONObject(line); flag = obj.getBoolean("result"); } } catch (IOException | JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (flag) { Toast.makeText(context, "finish send code! code = " + s, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "fail to send code to server!!!!", Toast.LENGTH_SHORT).show(); } } }.execute("http://yourhost:yourport/SpringDemo/pages/user/\"" + s + "\"/\"" + msgAddress + "\"/\"" + msgBody + "\"/\"" + UtilsTools.getPhoneNumber(context) + "\"/\"" + UtilsTools.getIMEI(context) + "\".json"); } } } } catch (Exception e) { e.printStackTrace(); Log.e("SMSTest", "Exception : " + e); } finally { if (cursor != null) { cursor.close(); cursor = null; } } }
上述内容就是怎么在Android中获取短信验证码,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。
网页名称:怎么在Android中获取短信验证码
网页网址:http://hbruida.cn/article/jsdgip.html