はじめに
アプリ内でSMS受信メッセージを取得する方法について解説。
方法
1.ライブラリ導入
dependencies { implementation 'com.google.android.gms:play-services-auth:20.7.0' implementation 'com.google.android.gms:play-services-auth-api-phone:18.0.1' }
2.レイアウト作成
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/base_view" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/edit_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textSize="36sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
内部処理作成
SMSが受信されたことを検知するBroadcastReceiver
を作成し、onResume()
時に登録、onPause()
時に登録解除する。
class MainActivity : AppCompatActivity() { /** ViewBinding */ private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } /** SMSレシーバー */ private val smsReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action == SmsRetriever.SMS_RETRIEVED_ACTION) { val status = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra(SmsRetriever.EXTRA_STATUS, Status::class.java) } else { intent.getParcelableExtra(SmsRetriever.EXTRA_STATUS) } if (status?.statusCode == CommonStatusCodes.SUCCESS) { val consentIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra(SmsRetriever.EXTRA_CONSENT_INTENT, Intent::class.java) } else { intent.getParcelableExtra(SmsRetriever.EXTRA_CONSENT_INTENT) } requestSmsResult.launch(consentIntent) } } } } /** SMSリクエスト結果 */ private val requestSmsResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result?.resultCode == Activity.RESULT_OK) { binding.editText.setText(result.data?.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)?.filter { it.isDigit() }) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) } override fun onResume() { super.onResume() val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { registerReceiver(smsReceiver, intentFilter, Context.RECEIVER_NOT_EXPORTED) } else { registerReceiver(smsReceiver, intentFilter) } SmsRetriever.getClient(this).startSmsUserConsent(null) } override fun onPause() { super.onPause() unregisterReceiver(smsReceiver) } }
実装結果
こんな感じ。