Observer pattern in Android Framework BroadcastReceiver and IntentFilter

In the Android framework, the Observer pattern is implemented through BroadcastReceiver and IntentFilter. 1. BroadcastReceiver: It is an Android component used to receive broadcast messages sent from the system or other applications. The BroadcastReceiver acts as an observer, observing the state of the system or events of other applications, and taking corresponding actions when the corresponding event is triggered. 2. IntentFilter: This is a filter used to specify the type of broadcast that BroadcastReceiver should receive. IntentFilter can filter based on broadcast actions, data types, URI schemes, categories, etc., ensuring that the BroadcastReceiver only receives broadcast messages related to them. The following is a simple example code that demonstrates how to use BroadcastReceiver and IntentFilter to implement the Observer pattern: //Custom Broadcast Recipient public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //The operation performed upon receiving a broadcast, such as popping up a notification Toast.makeText(context, "Received broadcast!", Toast.LENGTH_SHORT).show(); } } //Registering a broadcast recipient in an Activity or Service public class MainActivity extends AppCompatActivity { private MyBroadcastReceiver receiver; private IntentFilter filter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); receiver = new MyBroadcastReceiver(); filter = new IntentFilter(); Filter. addAction ("com. example. ACTION-MY_BROADCAST")// Define the received broadcast action //Register Broadcast Recipient registerReceiver(receiver, filter); } @Override protected void onDestroy() { super.onDestroy(); //Unregister broadcast recipients when an activity or service is destroyed unregisterReceiver(receiver); } } //Code for sending broadcasts public void sendBroadcast() { Intent intent = new Intent("com.example.ACTION_MY_BROADCAST"); //Add additional data or information to Intent sendBroadcast(intent); } Summary: The Observer pattern is a design mode throughout the Android framework. BroadcastReceiver and IntentFilter realize the communication between system components and applications by implementing the Observer pattern. The BroadcastReceiver, as an observer, filters the specified type of broadcast through the IntentFilter, and performs the corresponding operation after receiving the corresponding broadcast. Developers can achieve event notification and data transmission across components and applications by registering BroadcastReceiver and sending broadcasts.