Today we'll learn about Broadcast Receivers.
A Broadcast Receiver is a component used for catching external events and reacting to them. Events can be dispatched by other applications, servies, as well as the system. In the previous tutorials, we've already covered handling events using Intents. The components that we used as examples can also react to anonymous messages between applications using sendBroadcast() method.
Using Broadcast Receivers, it is possible to listen to Intents of other applications, change your application's behaviour based on the data, react to changes in the system and events of other applications.
Just like all activities extend Activity class and all services extend Service class, all broadcast receivers extend BroadcastReceiver class.
The class has a single callback method - onReceive().
When a message arrives to the receiver, Android calls onReceive() method and passes the Intent message to it. The Broadcast Receiver component is only active during the execution of this method. The process that's currently executing the code in onReceive() is considered top priority and will be saved, unless there's a critical lack in memory in the system.
When the program returns from onReceive(), the Broadcast Receiver object becomes inactive and the system basically thinks "this BroadcastReceiver's job is done" and will get rid of it if the memory taken by this object is needed for higher priority processes.
This sounds fair and all but it can actually cause a problem. For example, imagine if your onReceive() function creates a separate thread with a long process in it. While the process is still running, the onReceive() function will already be considered inactive by the system. If onReceive() is actually expecting a response from the thread, that response may never come since the BroadcastReceiver could get deleted by then.
But if there's a problem there's always a solution. Of course, everything depends on the situation, sometimes one solution might be more optimal than the other one.
One way to solve this would be to create a Service in the onReceive() function and let the Service do the work to keep the content of the process active during the whole operation process.
That's all for today. Next time we will do something practical.
Thanks for reading!