Skip to content

Instantly share code, notes, and snippets.

@maxost
Created September 5, 2017 02:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxost/d58272b095e827f4d5d90e29801c2c04 to your computer and use it in GitHub Desktop.
Save maxost/d58272b095e827f4d5d90e29801c2c04 to your computer and use it in GitHub Desktop.
Kotlin: sms receiver and rx bus in Android
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