Created
September 5, 2017 02:40
-
-
Save maxost/d58272b095e827f4d5d90e29801c2c04 to your computer and use it in GitHub Desktop.
Kotlin: sms receiver and rx bus in Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class Sms(val phone: String, val text: String) | |
object SmsBus { | |
private val bus by lazy { PublishSubject.create<Sms>() } | |
fun incomingSms(): Observable<Sms> = bus | |
fun postSms(sms: Sms) = bus.onNext(sms) | |
} | |
class SmsReceiver: BroadcastReceiver() { | |
override fun onReceive(context: Context?, intent: Intent?) { | |
val pdu = (intent?.extras?.get("pdus") as? Array<Any>)?.get(0) as? ByteArray | |
pdu?.let { | |
val message = SmsMessage.createFromPdu(it) | |
val sms = Sms( | |
phone = message.displayOriginatingAddress, | |
text = message.displayMessageBody | |
) | |
SmsBus.postSms(sms) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment