일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
- firebase-storage
- NoSuchMethodError
- JNI
- OZViewer
- ActivityResult-API
- gradle
- Android
- Galaxy Watch
- git-push
- mosquitto
- TIZEN
- BottomSheetDialog
- hung-up
- Dva
- Firebase
- ozd
- cloud-firestore
- socket-server
- socket-client
- mqtt
- 워치
- 오즈뷰어
- AWS
- Kotlin
- git
- Java8
- google-login
- firebase-database
- Flavors
- socket.io
- Today
- Total
Hyeyeon blog
[Android] Kotlin - SMS Receiver (인증번호 받기) 본문
1. AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
2. 사용하려는 Activity에 BroadcastReceiver 구현 및 등록
import android.content.BroadcastReceiver lateinit var receiver : BroadcastReceiver ... private fun initSmsReceiver() { receiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if ((intent!!.action as String) == Flag.SMS_RECEIVED) { val bundle = intent.extras val messages = parseSmsMessage(bundle!!) if (messages.isNotEmpty()) { val message = messages[0]!!.messageBody.toString() // 수신한 문자 메세지의 내용 val number = extractNumber(message) ... } } } } // 리시버 등록 val intentFilter = IntentFilter() intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED") this.registerReceiver(receiver, intentFilter) }
3. 문자메세지 파싱
import android.telephony.SmsMessage private fun parseSmsMessage(bundle: Bundle): Array{ val objects = bundle.get(" pdus")="" as="" array<*=""> val messages = arrayOfNulls (objects.size) for (i in 0 until objects.size) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val format = bundle.getString("format") messages[i] = SmsMessage.createFromPdu(objects[i] as ByteArray, format) } else { messages[i] = SmsMessage.createFromPdu(objects[i] as ByteArray) } } return messages }
4. String에서 number만 추출하기
private fun extractNumber(str: String): String {
var number = ""
val pattern = Pattern.compile("\\d+")
val matcher = pattern.matcher(str)
while (matcher.find()) {
number += matcher.group()
}
return number
}
5. onDestroy()에서 receiver 해지
override fun onDestroy() {
if (::receiver.isInitialized)
this.unregisterReceiver(receiver)
}
super.onDestroy()
}
'개발 > Android' 카테고리의 다른 글
[Android] Koin - Dependency Injection Library (0) | 2019.01.27 |
---|---|
[Android] Kotlin- Encode Base64 & Encrypt SHA-512 (0) | 2019.01.24 |
[Android] Kotlin - lateInit variable 초기화 여부 확인 (0) | 2019.01.22 |
[Android] Dependency Injection vs Service Locator (0) | 2019.01.22 |
[Android] Floating Button size (0) | 2019.01.17 |