本篇文章為大家展示了怎么在Android中獲取短信驗(yàn)證碼,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
為玉溪等地區(qū)用戶(hù)提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及玉溪網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、玉溪網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專(zhuān)業(yè)、用心的態(tài)度為用戶(hù)提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶(hù)的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
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) { //申請(qǐng)READ_SMS權(quán)限 ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_SMS}, 1); } mText = (TextView) findViewById(R.id.text); content = new SmsContent(new Handler(),this); //注冊(cè)短信變化監(jiān)聽(tīng) 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"); //讀取收件箱中指定號(hào)碼的短信 // 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排序的話,修改手機(jī)時(shí)間后,讀取的短信就不準(zhǔn)了 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的時(shí)候,不能主動(dòng)調(diào)用close()方法, 否則在Android 4.0+的系統(tǒng)上, 會(huì)發(fā)生崩潰 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; } }
上述方法未讀短信多了之后會(huì)同時(shí)上傳2條驗(yàn)證碼信息,可以根據(jù)cursor.getCount()來(lái)控制下。。。
下面第二種方法在oppo r9s上不見(jiàn)效果。。各位使用的小伙伴注意哦
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; } } }
上述內(nèi)容就是怎么在Android中獲取短信驗(yàn)證碼,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。