Hey Android Developers, this is part 2 of the Building blocks of the Android series. If you are new to this series please check out PART 1 where I covered the first half of the components.
In the previous blog, we have discussed Activities and Services. Now, we will see what is Broadcast Receivers and Content Providers.
Broadcast Receivers
Sometimes you want to listen to events happening in the Android system or events triggered by other apps. In that situation, you may think of creating a Service that runs indefinitely and checks every second Right? If no, you are great. If yes, we are in the same group.
The problem with the above method is we are wasting CPU resources and draining the battery. So what to do now? Broadcast Receiver to the rescue.
In Broadcast Receiver you define a block of code and specify the events that it should have to listen to. As I said earlier you can even listen to custom events triggered by other apps.
Let's see the code.
// MyBroadcastReceiver.kt
class MyBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// block of code
}
}
<!-- AndroidManifest.xml -->
<receiver android:name=".MyBroadcastReceiver"
android:permission="android.permission.SEND_SMS">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>
</intent-filter>
</receiver>
For more details: Check this doc
Content Providers
As every app runs in sandbox mode such that one app cannot communicate with another. But there are cases where we want to share data between apps.
For this, we can use Content Providers. It allows apps to share data from one app to another by a Provider and Resolver.
The app that provides data uses Content Providers and the one which consumes them uses Content Resolvers. I have created a small project on GitHub to demonstrate this. Here’s the link: https://github.com/SanjayDevTech/android-content-provider
For more details: Check this doc
Thank you so much for reading this article. Many more to come. : )