Android

Android 讀取簡訊驗證碼 帶入APP中

1.增加接收簡訊與讀取簡訊權限

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />

2.檢查是否用戶確認權限

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
     ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS), REQUEST_SMS_CODE)
} else {
     readSMSMessage()
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == REQUEST_SMS_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
         readSMSMessage()
     }
}

3.撰寫BroadCastReceiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsMessage
import java.util.regex.Pattern

class SMSReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val pdus = intent?.extras?.get("pdus") as Array<*>
        pdus.forEach {
            val sms = SmsMessage.createFromPdu(it as ByteArray)
            val body = sms.messageBody

            val patter = Pattern.compile("\\d{4}")
            val verification = patter.matcher(body)

            if (verification.find()) {
                val code = verification.group(0)
                val smsIntent = Intent("sms")
                smsIntent.putExtra("code", code)
                context?.sendBroadcast(smsIntent)
            }
        }
    }
}

4.在AndroidManifest聲明receiver

<receiver android:name=".SMSReceiver">
      <intent-filter android:priority="1000">
           <action android:name="android.provider.Telephony.SMS_RECEIVED" />
      </intent-filter>
</receiver>

5.將驗證碼塞入到EditText中

private fun readSMSMessage() {
      val receiver = object : BroadcastReceiver() {
          override fun onReceive(context: Context?, intent: Intent?) {
              editTextTextPersonName.setText(intent?.getStringExtra("code"))
          }
      }

      val filter = IntentFilter("sms")
      registerReceiver(receiver, filter)
}

6.效果展示

發表迴響