Junior — Middle
Have you had experience using the BroadcastReceiver component in your projects?
sobes.tech AI
Answer from AI
Yes, in Android projects I have used BroadcastReceiver to handle broadcast messages from the system or other applications. For example, BroadcastReceiver can be used to track changes in network state, receive SMS, or complete a file download.
Here's a simple example of a BroadcastReceiver that reacts to network state changes:
class NetworkChangeReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val noConnectivity = intent?.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false) ?: false
if (noConnectivity) {
Log.d("NetworkChangeReceiver", "No network connection")
} else {
Log.d("NetworkChangeReceiver", "Network is available")
}
}
}
Registration can be done either statically in the manifest or dynamically in code, depending on the task.