Android Broadcasts made easy with RxAndroid

Background

A common task in an Android application is to listen to system broadcasts and perform some action. For example you may want to listen to network connectivity changes and pause or resume some network communication depending on the network state.

Normally this involves implementing a BroadcastReceiver then registering it with Context.registerReceiver and unregistering it with Context.unregisterReceiver in the appropriate life-cycle methods. While it is not a lot of code by itself, it can quickly become tiring to write and maintain if receivers are used many times throughout an application.

For this reason we can simplify the procedure significantly using a combination of Kotlin extension functions, RxAndroid and the Android Lifecycle-Aware Components library.

First steps

Our first step is to define a observeBroadcasts extension function on Context, this will allow us to use it anywhere we have a Context object available, be it in Activity or in a Service.

Example usage in an Activity:

Adding lifecycle awareness

The previous example improved our code by removing the need to implement a BroadcastReceiver and hiding the registration flow behind a standard Rx Observable. We can however take one step further by utilizing the recently added LifecycleObserver interface and related methods in the Android Architecture Components.

This new subscribeToBroadcastsOnLifecycle is called only from Activity.onCreate with no further interaction necessary.

Example usage in an Activity:

End notes

  • Typical blog-code disclaimer: The code snippets above are only intended as inspiration and do not include all recommended error handling code.
  • subscribeToBroadcastsOnLifecycle currently only uses onStart and onStop but should be easy to extend to support any appropriate lifecycle method pairs.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s